How do I properly return a char * from an Unmanaged DLL to C#?

后端 未结 5 894
生来不讨喜
生来不讨喜 2021-01-06 08:57

Function signature:

char * errMessage(int err);

My code:

[DllImport(\"api.dll\")]       
internal static extern char[] errMessage(int err);         


        
5条回答
  •  暖寄归人
    2021-01-06 09:33

    A simple and robust way is to allocate a buffer in C# in the form if a StringBuilder, pass it to the unmanaged code and fill it there.

    Example:

    C

    #include 
    
    int foo(char *buf, int n) {
       strncpy(buf, "Hello World", n);
       return 0;
    }
    

    C#

    [DllImport("libfoo", EntryPoint = "foo")]
    static extern int Foo(StringBuilder buffer, int capacity);
    
    static void Main()
    {
        StringBuilder sb = new StringBuilder(100);
        Foo(sb, sb.Capacity);
        Console.WriteLine(sb.ToString());
    }
    

    Test:

    Hello World
    

提交回复
热议问题