Equivalent to char * in C #

I have a dll written in C ++. And I p / call to call the functions.

I have this C ++ declaration.

int dll_registerAccount(char* username, char* password);

      

I made this dllimport declaration:

[DllImport("pjsipDlld")]
static extern int dll_registerAccount(IntPtr username, IntPtr password);

      

Will my DllImport be the C ++ equivalent using IntPtr?

Thanks a lot for any advice,

+2


source to share


6 answers


The C # way to do this is to let the marshaller process the elements char*

while working with the string:

[DllImport("pjsipDlld")]
static extern int dll_registerAccount(
    [MarshalAs(UnmanagedType.LPStr)]string username,
    [MarshalAs(UnmanagedType.LPStr)]string password);

      



Replace LPStr

with LPWStr

if you are working with wide characters.

+23


source


StringBuilder for char * since length is unknown?



[DllImport("pjsipDlld")]
static extern int dll_registerAccount(StringBuilder username, StringBuilder password);

      

+2


source


    [DllImport("pjsipDlld", CharSet = CharSet.Ansi)]
    static extern int dll_registerAccount(string username, string password);

      

+1


source


I launched your C ++ line via P / Invoke :

public partial class NativeMethods {

    /// Return Type: int
    ///username: char*
    ///password: char*
    [System.Runtime.InteropServices.DllImportAttribute("<Unknown>", EntryPoint="dll_registerAccount")]
public static extern  int dll_registerAccount(System.IntPtr username, System.IntPtr password) ;

}

      

So you were right, it should work. But there are several automatic marshaling, you may only be able to do:

[DllImport("pjsipDlld")]
static extern int dll_registerAccount(string username, string password);

      

See MSDN page about default marshaling and override it.

0


source


Be aware of calling conventions, it worked. In my case, I need to call a C ++ DLL, but with a C style export that uses the calling convention cdecl

. If you have the luxury of having a native Visual Studio solution, go to Properties -> C / C ++ -> Advanced and find it under Calling Convention. This fix it for me:

[DllImport(DllName, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
// bool MyFunction(char* fileName) <-- From the DLL
static extern bool MyFunction(string fileName);

      

0


source


  [DllImport("DLL loction"),EntryPoint = "dll_registerAccount", CallingConvention = CallingConvention.Cdecl)]
  [return : MarshalAs(UnmanagedType.I4)]
  static extern int dll_registerAccount(
                       [MarshalAs(UnmanagedType.LPStr)]string username,
                       [MarshalAs(UnmanagedType.LPStr)]string password);

      

  • 'cdecl' is the default calling convention for C and C ++ programs
  • Refer to these doc1 for more information
0


source







All Articles