6

I am trying to pass a string from C# to a C DLL. From what I have 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 someone advise me of where I have went 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);
}
DaveShaw
  • 52,123
  • 16
  • 112
  • 141
integra753
  • 271
  • 1
  • 5
  • 19

3 Answers3

3

Declare your external method as:

public static extern bool StreamReceiveInitialise(string filepath);
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
1

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 is the default, but I like being explicit).

Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
1

Use a StringBuilder in place of char*. See this

[DllImport("Source.dll")]
public static extern bool StreamReceiveInitialise(StringBuilder filepath);
Community
  • 1
  • 1
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92