-
July 21st, 2011, 06:39 AM
#1
Pass an Array in a Struct from Managed to Unmanaged
Hi All,
I have an unmanaged C function that takes in a struct that contains a fixed length array. I have declared the array in both C and C++/CLI so the type conversion should be handled implicitly however I must have a mistake somewhere.
When I debug, the array that is passed into the unmanaged code is offset by 16 bytes (seemingly the header information for the array). Data can be returned to the managed code so long as the offset is used.
Here is a cut down version of the unmanaged struct:
Code:
typedef struct test_struct{
uint8_t Array[100];
} test_struct;
and the corresponding managed version
Code:
[StructLayout(LayoutKind::Sequential)]
ref struct test_struct {
[MarshalAs(UnmanagedType::ByValArray,SizeConst=100)]
static array<unsigned char>^ Array;
};
This is the prototype for the unmanaged function
Code:
int function_test(test_struct * test)
and the call from managed code
Code:
int Test (test_struct^% pTest) {
test_struct test;
test.Array = gcnew array<unsigned char>(100);
test.Array[0] = 2;
int result = function_test (test);
pTest = %test;
return result;
}
At the time of the call, the struct indicates:
Array[0] = 2
Array[1] = 0
Array[2] = 0
etc
Then inside the call the arguement changes to
Array[0 to 15] = Random data
Array[16] = 2
Array[17] = 0
Array[18] = 0
etc
Thanks in advance.
-
July 21st, 2011, 06:55 AM
#2
Re: Pass an Array in a Struct from Managed to Unmanaged
Why do you use PInvoke in C++/CLI? You can call unmanaged C function directly from C++/CLI exactly by the same way, as from C or C++ program. Just fill test_struct structure and call function_test without using PInvoke.
-
July 21st, 2011, 08:22 AM
#3
Re: Pass an Array in a Struct from Managed to Unmanaged
Originally Posted by Alex F
Why do you use PInvoke in C++/CLI? You can call unmanaged C function directly from C++/CLI exactly by the same way, as from C or C++ program. Just fill test_struct structure and call function_test without using PInvoke.
I tried to simplify the problem too much in my initial description.
The call is made from C++/CLI to a win 32 dll wrapper which sits around the C functions themselves. I'm therefore using dll export and import to get access to the dll wrapper functions.
This method works fine for the other 200 functions or so, but none of them take an array as part of a struct parameter which is where I am struggling.
-
July 21st, 2011, 08:39 AM
#4
Re: Pass an Array in a Struct from Managed to Unmanaged
Do you know to call Dll function from native C/C++? Just do the same in C++/CLI. Add .lib to the linker dependencies list, include required h-file and call unmanaged function directly.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|