Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using C function in C#

i have a dll, built with mingw
one of the header files contains this:

extern "C" {
  int get_mac_address(char * mac); //the function returns a mac address in the char * mac
}

I use this dll in another c++ app, built using Visual C++ (2008SP1), not managed, but plain c++ (simply include the header, and call the function)

But now I have to use it in a C# application

The problem is that i can't figure out how exactly (i'm new in .net programming)

this is what i've tried

public class Hwdinfo {
    [DllImport("mydll.dll")]
    public static extern void get_mac_address(string s);
}

When i call the function, nothing happens

(the mydll.dll file is located in the bin folder of the c# app, and it gives me no errors or warnings whatsoever)

like image 477
Andrei S Avatar asked May 13 '10 15:05

Andrei S


Video Answer


4 Answers

I think you need to define the extern as:

public class Hwdinfo { 
    [DllImport("mydll.dll")] 
    public static extern int get_mac_address(out string s); 
} 

You should match both the return argument type on the function (int) as well as mark the string parameter as an out parameter so that your C# code is generated to expect to receive a value from the called function, rather than just passing one in.

Remember, strings in C# are treated as immutable, this behavior extends to external calls as well.

like image 196
LBushkin Avatar answered Oct 03 '22 04:10

LBushkin


To use string output parameters with DllImport, the type should be StringBuilder.


public class Hwdinfo {
    [DllImport("mydll.dll")]
    public static extern int get_mac_address(StringBuilder s);
}

Here's an MSDN Article about using Win32 dlls and C#:
http://msdn.microsoft.com/en-us/magazine/cc164123.aspx

like image 32
The Moof Avatar answered Oct 03 '22 04:10

The Moof


If you expect your MAC address to come through your string parameter, I guess you had better to make it a reference.

public class Hwdinfo { 
    [DllImport("mydll.dll")] 
    public static extern int get_mac_address(out string s); 
} 

Or something like so.

like image 36
Will Marcouiller Avatar answered Oct 03 '22 05:10

Will Marcouiller


You can find lots of examples here: http://pinvoke.net/

I suspect that you your best hints would come from something like: http://pinvoke.net/default.aspx/shell32.SHGetSpecialFolderPath

like image 35
John Fisher Avatar answered Oct 03 '22 04:10

John Fisher