How to correctly return char * from an unmanaged DLL in C #?

Functional Signature:

char * errMessage (int err);

My code is:

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

This returns an error:

Cannot marshal 'return value': Invalid managed / unmanaged type combination.

What am I doing wrong? Thanks for any help.

+3
source share
5 answers

try the following:

[DllImport("api.dll")]
[return : MarshalAs(UnmanagedType.LPStr)]
internal static extern string errMessage(int err);
...
string message = errMessage(err);

I believe C # is smart enough to handle a pointer and returns a string to you.

Edit: MarshalAs attribute added

+2
source

# , StringBuilder, .

:

#include <string.h>

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

#

[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());
}

:

Hello World
+7

. . IntPtr, Marshal.PtrToString *, String.

+5

, , . . "string" , P/Invoke CoTaskMemFree() . . XP, Vista Win7.

. , free(), . , , IntPtr Marshal.PtrToStringAnsi(). , , Taskmgr.exe. , , .

+4

String . CharSet Ansi

0

Source: https://habr.com/ru/post/1723252/


All Articles