开发者

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?


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.


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) ;


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) ;


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);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜