Hello,
As soon as you need the C DLL to modify the string passed, you cannot use
default string marshaling - StringBuilders are not supported in structs.
What I'd do is:
- Declaring the str member as IntPtr.
- Allocating necessary buffer space with Marshal.AllocHGlobal.
- Passing the pointer to the allocated memory in the "str" member
- Getting modified string data to a .NET string with Marshal.PtrToStringAnsi
- Freeing the allocated buffer with Marshal.FreeHGlobal
[quoted text, click to view] "Alvaro Enriquez de Luna" <alvaro.em@gmail.com> wrote in message
news:1140784937.876809.209380@i40g2000cwc.googlegroups.com...
> Hello.
> I have a DLL written in C. In this DLL i need a function to modify a
> char * passed from a C# program inside a struct. I have reduced the
> code to only one struct with one char *, but when i try to call the
> funcion, i obtain this exception:
>
> "Cannot marshal field 'str' of type 'memmap': Invalid managed/unmanaged
> type combination (Arrays fields must be paired with ByValArray or
> SafeArray)."
>
> Here is the relevant part of the C DLL:
>
> struct memmap
> {
> char str[256];
>
> };
>
> __declspec(dllexport) void ModifyStruct(struct memmap *mem)
> {
> strcpy(mem->str, "Everything works!\n");
>
> }
>
> And these are C# definitions
>
> class MyClass
> {
> [...]
>
> [StructLayout(LayoutKind.Sequential)]
> public struct memmap
> {
> [MarshalAs(UnmanagedType.LPStr, SizeConst=256)] public
> byte[] str;
> }
>
> public memmap mem;
>
> [DllImport("MyDLL.dll")]
> public static extern void ModifyStruct(ref memmap mem);
>
> [...]
>
> }
>
> This is the call where i get the exception:
>
> MyClass.ModifyStruct(ref myObject.mem);
>
> Does anybody know where could be the error? Please help.
>
> Thank you in advance.
>