Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a const char* to a C function from C#?

I try to call a plain C-function from an external DLL out of my C#-application. This functions is defined as

void set_param(const char *data) 

Now I have some problems using this function:

  1. How do I specify this "const" in C#-code? public static extern void set_param(sbyte *data) seems to miss the "const" part.

  2. How do I hand over a plain, 8 bit C-string when calling this function? A call to set_param("127.0.0.1") results in an error message, "cannot convert from 'string' to 'sbyte'"*.

like image 568
Elmi Avatar asked May 04 '15 11:05

Elmi


People also ask

Can a char * be passed as a const * argument?

char** cannot be assigned to const char* b/c char* and const char* do not seem to be compatible.

What does char * const mean in C?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

Can you assign a const char * to a string?

You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .


1 Answers

It looks like you will be using the ANSI char set, so you could declare the P/Invoke like so:

[DllImport("yourdll.dll", CharSet = CharSet.Ansi)] public static extern void set_param([MarshalAs(UnmanagedType.LPStr)] string lpString); 

The .NET marshaller handles making copies of strings and converting the data to the right type for you.

If you have an error with an unbalanced stack, you will need to set the calling convention to match your C DLL, for example:

[DllImport("yourdll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] 

See pinvoke.net for lots of examples using Windows API functions.

Also see Microsoft's documentation on pinvoking strings.

like image 100
Matthew Watson Avatar answered Sep 29 '22 11:09

Matthew Watson