5

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)

Andrei S
  • 6,486
  • 5
  • 37
  • 54
  • 1
    What are you expecting to happen? You aren't returning anything. If you are wanting to get the parameter back out you may need to pass it as ref string s or out string s. – Stephan May 13 '10 at 15:25

6 Answers6

10

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.

LBushkin
  • 129,300
  • 32
  • 216
  • 265
3

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.

Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162
3

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

The Moof
  • 794
  • 4
  • 10
1

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

John Fisher
  • 22,355
  • 2
  • 39
  • 64
1

Strings in .NET are immutable so try:

public class Hwdinfo { 
    [DllImport("mydll.dll")] 
    public static extern int get_mac_address(char[] s); 
}
Daniel Renshaw
  • 33,729
  • 8
  • 75
  • 94
1

C# PInvoke out strings declaration

This suggests you might try using a StringBuilder as your parameter instead of a string. If that doesn't work then an out parameter would be my next choice.

Community
  • 1
  • 1
Stephan
  • 5,430
  • 2
  • 23
  • 31