1

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?

1

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you also tell me how to write the DllImport part?
It can be as simple as [DllImport("mylibrary.dll")] but all other parameters depend on how it is defined and on the library.
0

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

Comments

0

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.