473,805 Members | 2,027 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to return array of structs from unmanaged DLL to C#?

Mates,
the problem is pretty simple, but I'm unable to manage it... Therefore
asking you for help.

Situation:
Have managed code in C# and unamanged code in C++ DLL.
I need to make a call from C# to a function exported by the DLL.
Moreover, I have following struct (in C# and C++, as well):
struct myStruct {
unsigned int val1;
unsigned int val2;
}

What I need:
The C# function declares two empty variables (one for the array itself and
second one for the number of items returned in the array) and passes them
using "ref" keyword to C++ function. The C++ function determines the number
of array elements that will be returned, dynamically allocates memory,
creates the array of structs and passes it (along with the size of the array
itself) to the C# function.

Assumptions:
- C# code (the calling one) doesn't know the number of items in the array
that will be returned
- C# must NOT use unsafe code
- the number of items in the array may vary, but will always be >0

I know that Marshalling/Serialization will be required, but I can't find the
right code. Below, you can see my current C++ and C# code. I'm able to return
and marshal only 1 element. Any ideas?

// C++ code - currently returns only 1 element
struct test {
unsigned int val1;
unsigned int val2;
};

extern "C" __declspec(dlle xport) void Test(test** pArray, int* pSize)
{
*pArray = (test*) CoTaskMemAlloc( sizeof(test) * 1);
for (unsigned int i = 0; i < 1; i++)
{
(*pArray + i)->accountID = i;
(*pArray + i)->period = i+1;
(*pArray + i)->cycle = i+2;
(*pArray + i)->cellType = i+3;
}
*pSize = 1;
}

// C# code
[StructLayout(La youtKind.Sequen tial)]
public class clTest
{
public uint val1;
public uint val2;
}

[DllImport("some dll.dll")]
public static extern void Test(out IntPtr tst, ref int pSize);

IntPtr buffer;
int size = 0;

Test(out buffer, ref size);
if (size 0)
{
clTest arr = new clTest();
Marshal.PtrToSt ructure(buffer, arr );
Marshal.FreeCoT askMem(buffer);
}
Sep 24 '08 #1
1 4896
pls, anyone?

"Darkriser" wrote:
Mates,
the problem is pretty simple, but I'm unable to manage it... Therefore
asking you for help.

Situation:
Have managed code in C# and unamanged code in C++ DLL.
I need to make a call from C# to a function exported by the DLL.
Moreover, I have following struct (in C# and C++, as well):
struct myStruct {
unsigned int val1;
unsigned int val2;
}

What I need:
The C# function declares two empty variables (one for the array itself and
second one for the number of items returned in the array) and passes them
using "ref" keyword to C++ function. The C++ function determines the number
of array elements that will be returned, dynamically allocates memory,
creates the array of structs and passes it (along with the size of the array
itself) to the C# function.

Assumptions:
- C# code (the calling one) doesn't know the number of items in the array
that will be returned
- C# must NOT use unsafe code
- the number of items in the array may vary, but will always be >0

I know that Marshalling/Serialization will be required, but I can't find the
right code. Below, you can see my current C++ and C# code. I'm able to return
and marshal only 1 element. Any ideas?

// C++ code - currently returns only 1 element
struct test {
unsigned int val1;
unsigned int val2;
};

extern "C" __declspec(dlle xport) void Test(test** pArray, int* pSize)
{
*pArray = (test*) CoTaskMemAlloc( sizeof(test) * 1);
for (unsigned int i = 0; i < 1; i++)
{
(*pArray + i)->accountID = i;
(*pArray + i)->period = i+1;
(*pArray + i)->cycle = i+2;
(*pArray + i)->cellType = i+3;
}
*pSize = 1;
}

// C# code
[StructLayout(La youtKind.Sequen tial)]
public class clTest
{
public uint val1;
public uint val2;
}

[DllImport("some dll.dll")]
public static extern void Test(out IntPtr tst, ref int pSize);

IntPtr buffer;
int size = 0;

Test(out buffer, ref size);
if (size 0)
{
clTest arr = new clTest();
Marshal.PtrToSt ructure(buffer, arr );
Marshal.FreeCoT askMem(buffer);
}
Sep 29 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6974
by: Richard A. Lowe | last post by:
I'm successfully using SendInput to emulate mouse events for a legacy app, delcared like so: public extern static int SendInput( int theCount, ref INPUT pInputs, int theSize ); From the MSDN docs, SendInput appears to take an array of inputs:
8
3618
by: Mas L via DotNetMonster.com | last post by:
Hi, I have a c++ source code which I can compile to be a DLL (in VS.NET 2003). And I need to use it in a C# program. After I compiled/build the C++ code to a DLL, I add it as a Reference in my C# program. When I look at the reference and I double click to view it in the objec browser , I see only structs , without their members. And I don't see methods.
4
4880
by: ned | last post by:
I have been having a lot of problems with an array of structures embedded in another structure in C++ .NET and have boiled it down to this very simple example: Try the following steps, it will only take 5 minutes: 1) Create a new C++ .NET Windows Form project. 2) Create a new .h file and put in it:
7
6444
by: heddy | last post by:
I have an array of objects. When I use Array.Resize<T>(ref Object,int Newsize); and the newsize is smaller then what the array was previously, are the resources allocated to the objects that are now thown out of the array released properly by the CLI?
6
8154
by: DaTurk | last post by:
Hi, I'm coding a layer into my application using CLI, between a unmanaged and a c# layer. So, I have to marshal some unmanaged c++ structures to structures usable in c#. My solution was to marshal the unmanaged C++ structures to CLI ref structs, these being usable in the c# layer. Why I did it this way is I want all of the business logic in the CLI layer. Because he c# layer is purely presentaion.
13
2078
by: =?Utf-8?B?U2hhcm9u?= | last post by:
I have the following managed C++ function (VC++ 2005 (C++/CLI) System::Array^ ManagedCppClass::GetData() { BYTE* pData; int len; m_pureNativeCPPObj->GetData(pData, len); // Get the data buffer from unmanaged class. array<byte>^ Arr = gcnew array<byte>(len);
6
8968
by: =?Utf-8?B?QWxleGFuZGVyZmU=?= | last post by:
Hi, I have a C# program that uses an unmanaged dll that has a function similar to the signature below : void f(out MyStruct arr, out int num); // num = actual array length returned The array must be allocated (with known max length = 10) before the call to the dll function (the dll just fills it ,with no allocations). The definitions of Mystruct and :
2
4360
by: jonpb | last post by:
Using .NET 3.5, I need to pass an array of structs as parameter to a C++ unmanaged function. The C++ dll stores some data in an unmanaged cache, the function writes the values into the array of structs. The array of structs are allocated by C#. If I pass the array without 'ref' it works fine on the C++ side, but after returning to C# the array struct values are all zero. If I pass with 'ref' the application crashes. If I use a class...
0
1661
by: mjaaland | last post by:
Hi! I've been working with DLLimports passing structs and various other parameters to unmanaged code. I had problems earlier sending pointer to structs to the unmanaged code, and this forum solved it for me (using the ref keyword etc). I now encountered a function that takes a pointer to an array as a parameter, and this array consists of other pointers, to structs. Horrible isn't it? I have no way of modifying the unmanaged code, I...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10356
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10361
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10103
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5676
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4316
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3839
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.