all groups > dotnet interop > february 2006 >
You're in the

dotnet interop

group:

Marshaling char *... HELP, PLEASE!



Marshaling char *... HELP, PLEASE! Alvaro Enriquez de Luna
2/24/2006 4:42:17 AM
dotnet interop: 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.
Re: Marshaling char *... HELP, PLEASE! Dmytro Lapshyn [MVP]
3/1/2006 12:00:00 AM
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]
AddThis Social Bookmark Button