Conor Watson
Conor Watson

Reputation: 617

How to convert between a C# String and C Char pointer

I have a large library written in C that I would like to use as a DLL in a C# program. Most of the C code will be used by the libraries own functions, but I do need one function to be able to be called from the C# project.

So there's an example C function below

__declspec(dllexport) char* test(char* a){
    char* b = "World";
    char* result = malloc(strlen(a) + strlen(b) + 1);

    strcpy(result, a);
    strcpy(result, b);

    return result;
}

Now in the C# code I have got using System.Running.InteropServices; and also [DllImport("mydll.dll")] but I'm not sure how to declared the function.

public static extern char* test(char* a); obviously doesn't work because C# doesn't support pointers like C does.

So how should I pass a string to this C function and have it return a string as well?

Upvotes: 2

Views: 4718

Answers (1)

Asik
Asik

Reputation: 22123

You're looking for a MarshalAs attribute:

   [DllImport("mydll.dll")]
   static public int test([MarshalAs(UnmanagedType.LPStr)]String a);

As for returning a dynamically allocated C string, bad idea. How will you reliably de-allocate the string? It's a recipe for a memory leak. Allocate a byte array in C#, pin it and pass it to the C code along with its size so the C code can copy the result into it. Then convert to a string using System.Text.Encoding.ASCII.GetString().

Upvotes: 9

Related Questions