简体   繁体   中英

passing string from C++ to C# using void pointer

I am having C++ code like this just to try out to get the string to C# application from c++ dll.

int GetValue(void *pBuffer)
{
    int x = 0;
    String^ temp;
    temp = "TestStringtest1test2";

    memcpy(pBuffer, &temp,sizeof(temp));

    Console::WriteLine(temp);
    return x;
}

on c# side all I am doing is

[DllImport("Cplusplusapp.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int GetValue(StringBuilder pBuffer); 

  StringBuilder Buffer = new StringBuilder(100);
  int x = GetValue(Buffer);
  Console.WriteLine(Buffer);

I have tried marshalling and various other suggestions but I am not able to understand why I am getting garbage values.Its fairly simple but what is that I am missing.

Address of temp IS NOT string itself then memcpy won't work as expected. Moreover sizeof(String) will return size of System.String object (4 bytes on 32 bit machine), not string length.

If you need to copy a value from a managed string to an unmanaged pointer you have to follow next steps.

First of all System.String is always UNICODE then you won't have char* but wchar_t* (but you can convert it to what you need with usual helper macros). To convert a string from System.String to wchar_t* call Marshal::StringToBSTR() :

String^ temp = L"My string";
BSTR bstr = Marhshal::StringToBSTR(temp);
memcpy(pBuffer, bstr, SysStringLength(bstr));
Marshal::FreeBSTR(bstr);

Of course if you do not need to use a System.String you can skip all of these simply not assigning your string to System.String . Change it to wchar_t* or char* according to how you'll import that function ( CharSet.Ansi or not), take a look to other Marshal::StringToXYZ functions, I would create e temporary string from System::String and then I would strcpy to destination buffer (check functions with Ansi suffix for char* versions). See this post here on SO for an example of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM