Passing a string from C # to C DLL

I am trying to pass a string from C # to C DLL. From what I read, .NET should do the conversion from string to char * for me, however I get "error CS1503: Argument" 1 ": cannot convert from" string "to" char * ". Can anyone advise me, where did I go wrong? Thanks.

C # code

[DllImport("Source.dll", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] public static unsafe extern bool StreamReceiveInitialise(char* filepath); const string test = "test"; // This method that will be called when the thread is started public void Stream() { if (StreamReceiveInitialise(test)) { } } 

C dll

 extern "C" { __declspec(dllexport) bool __cdecl StreamReceiveInitialise(char* filepath); } 
+6
source share
3 answers

Declare your external method as:

 public static extern bool StreamReceiveInitialise(string filepath); 
+3
source

Do it like this:

 [DllImport("Source.dll", CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.ANSI)] static extern bool StreamReceiveInitialise([MarshalAs(UnmanagedType.LPStr)] string filepath); 

(Marshalling as UnmanagedType.LPStr by default, but I like to be explicit).

+1
source

Use StringBuilder instead of char *. See this

 [DllImport("Source.dll")] public static extern bool StreamReceiveInitialise(StringBuilder filepath); 
+1
source

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


All Articles