delete_this_account
delete_this_account

Reputation: 2446

C# char pointer, Calling C++ dll functions and passing parameters

I want to call a C function from C#. C function is inside a dll. The function I want to call is declared as follows:

int raxml_main(int argc, char*[] argv);

The problem is I am new to C# and I don not know how to convert string[] args to char*[] argv. Is it possible? Any idea?

Upvotes: 1

Views: 3086

Answers (4)

delete_this_account
delete_this_account

Reputation: 2446

I combined two answers and it worked. Here is the solution:

[System.Runtime.InteropServices.DllImportAttribute("RaxmlDLL.dll", EntryPoint="raxml_main")]
public static extern  int raxml_main(int argc, string[] argv) ;

Upvotes: 0

Aliostad
Aliostad

Reputation: 81660

try using below:

public static extern int raxml_main(int count, string[] argv);

You need to decorate with appropriate DllImport.

Sometimes string has to be declared as StringBuilder but I doubt it is necessary here since you are sending the string.

Upvotes: 4

Falcon
Falcon

Reputation: 3160

You can use tools like the PInvoke Interop Assistant to generate the signatures you need. In your case it is:

[System.Runtime.InteropServices.DllImportAttribute("yours.dll", EntryPoint="raxml_main")]
public static extern  int raxml_main(int argc, System.IntPtr[] argv) ;

Upvotes: 0

Matthew
Matthew

Reputation: 25743

You can convert the string to a byte array, but you have to make sure that the encoding in the raxml_main function is compatible (ascii encoding may be more approperiate).

This is just some code I found online.

 // C# to convert a string to a byte array.
 public static byte[] StrToByteArray(string str)
 {
     System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
     return encoding.GetBytes(str);
 }

Upvotes: -1

Related Questions