简体   繁体   中英

What do I need to do reference a c++ dll from a C# application?

The C++ dll is using Win32 to read from and write data to the Serial Port. I need that data in my C# application. Is it simply a case of referencing the dll the way I would any other dll written in C#, import that and then call the methods in it? Or do I need to do something differently?

You need to use PInvoke if this DLL is not a COM library

Basically, every function exported by the DLL need to be defined using the syntax required. This is an example of the declaration required to access the function InternetGetConnectedState from wininet.dll

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( out int Description, int ReservedValue ) ;

After that declare you could call the function from your C# code in this way

public static bool IsConnectedToInternet( )
{
    try
    {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }
    catch 
    {
        return false;
    }
}

Of course, your DLL shuld be visible from your application (same folder or path)

Search term you are looking for is PInvoke.

Essentially you need to declare methods in C# class that refer to external C++ implementation.

Something like this (from MSDN sample ):

class PlatformInvokeTest
{
    [DllImport("msvcrt.dll")]
    public static extern int puts(string c);
    [DllImport("msvcrt.dll")]
    internal static extern int _flushall();

    public static void Main() 
    {
        puts("Test");
        _flushall();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM