Interop sending string from C# to C++

前端 未结 5 1173
醉酒成梦
醉酒成梦 2020-12-11 23:25

I want to send a string from C# to a function in a native C++ DLL.

Here is my code: The C# side:

[DllImport(@\"Native3DHandler.dll\", EntryPoint = \"         


        
相关标签:
5条回答
  • 2020-12-11 23:44

    If you just want to send a string, just declare func1's parameter as a string. If you want to receive a string, declare it as a StringBuilder and allocate enough buffer space for what you want to receive.

    0 讨论(0)
  • 2020-12-11 23:50

    Your declaration is wrong. The parameter should be of type string, and you should set the character set encoding to Ansi, like so:

    [DllImport(@"Native3DHandler.dll", EntryPoint = "#22", 
        CharSet = CharSet.Ansi)]
    private static extern void func1(string path);
    

    This assumes that you are not modifying the contents of the path variable in your C++ code. Then, you pass the string parameter directly (no need for the wrapper).

    0 讨论(0)
  • 2020-12-11 23:51

    It looks like you have 2 issues. The first is your native C++ uses an ANSI string but you are specifying unicode. Secondly, it's easiest to just marshal a string as a string.

    Try changing the DllImport to the following

    [DllImport(
      @"Native3DHandler.dll", 
      EntryPoint = "#22",  
      CharSet = CharSet.Ansi)]
    private static extern void func1(void* something, [In] string path);
    
    0 讨论(0)
  • 2020-12-12 00:00

    Works fine for me with no extra marshalling instructions in VS2008:

    C# side:

    [DllImport("Test.dll")]
    public static extern void getString(StringBuilder theString, int bufferSize);
    
    func()
    {
      StringBuilder tstStr = new StringBuilder(BufSize);
      getString(tstStr, BufSize);
    }
    

    C++ side:

    extern "C" __declspec(dllexport) void getString(char* str, int bufferSize)
    {
      strcpy_s(str, bufferSize, "FOOBAR");
    }
    
    0 讨论(0)
  • 2020-12-12 00:00

    Default Marshaling for Strings http://msdn.microsoft.com/en-us/library/s9ts558h.aspx

    0 讨论(0)
提交回复
热议问题