Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Function signature:

char * errMessage(int err);

My code:

[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.

like image 739
IronicMuffin Avatar asked Dec 01 '22 11:12

IronicMuffin


1 Answers

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 <string.h>

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
like image 60
dtb Avatar answered Dec 03 '22 01:12

dtb