Marshalling C dll code into C#

别来无恙 提交于 2019-12-06 13:34:19

Don't pass a StringBuilder reference to a unmanaged method that takes a char*. StringBuilder content is unicode (wchar).

Instead, replace the StringBuilder parameter with and IntPtr parameter and allocate a appropriate size buffer using Marshal.AllocHGlobal.

Also I don't think passing a StringBuilder to unmanaged code using "ref" is supported by the .Net marshaller.

You mentioned that the 'char **enc' parameter may be modified by the callee, this could be causing the 'SystemAccessViolation' error. A StringBuilder can be dereferenced and modified by the callee, provided it does not exceed the StringBuilders capacity.

StringBuilder should not be passed by reference using out or ref.

    //...
    [In,Out,MarshalAs(UnmanagedType.LPStr)] ref StringBuilder encoding,
    //...

Remove the ref keyword from the encoding parameter that is of type StringBuilder. That is what is probably causing your SystemAccessViolation.

I was trying to pass a string from C++ to C# in Unity. And all I got was gibberish. Finally after I saw your comment @popcatalin I discovered the solution using AllocHGlobal from C# to allocate memory for the string.

This is my C++ function:

extern "C" void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API TestString(char* str, int len)
{
    strcpy_s(str, len, "C++ String!!! UniversalCpp");
    return;
}

This is at the top of the C# script in Unity:

#if WRCCPP
    [DllImport("UniversalWRCCpp", CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport("UniversalCpp", CallingConvention=CallingConvention.Cdecl)]
#endif
    private static extern void TestString(IntPtr str, int len);

private IntPtr myPtr = IntPtr.Zero; // Pointer to allocated memory

And this is my C# script in Unity calling that function:

int sizeInBytes = 100;
myPtr = Marshal.AllocHGlobal(new IntPtr(sizeInBytes));
TestString(myPtr, sizeInBytes);
Debug.Log("ANSI " + Marshal.PtrToStringAnsi(myPtr)); // This prints the correct format
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!