简体   繁体   中英

How to get refference to the unmanaged (not COM) interface in C#?

I have a native DLL which is implementing some API. The C++ header looks like this:

class CAPIInterface
{
public:
    virtual int    __stdcall Release()=0;
    virtual LPCSTR __stdcall ErrorDescription(const int code)=0;
    virtual int  __stdcall Login(const int login,LPCSTR password)=0;
}

In C++ a pointer to the interface is acquired this way:

typedef int (*APICreate_t)(int version,CAPIInterface **api);

pfnAPICreate =reinterpret_cast<APICreate_t>(::GetProcAddress(hlib,"APICreate"));
CAPIInterface *api=NULL;
if(pfnAPICreate) (*pfnAPICreate)(version,&api);

The methods of the interface are called like this:

api->Login(123,"password");

Now I need to load this native DLL and use the API in my C# program. I managed to load the DLL and acquire the pointer to the native interface this way:

    public static class GlobalMembers
    {
        [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi)]
        public delegate int APICreate_t(time_t version, out IntPtr api);
    }
    ptr_pfnAPICreate = NativeMethods.GetProcAddress(hlib,"APICreate");
    pfnAPICreate = (GlobalMembers.APICreate_t)Marshal.GetDelegateForFunctionPointer(ptr_pfnAPICreate, typeof(GlobalMembers.APICreate_t));
    pfnAPICreate(version, out mptr);

But now I'm not sure how to map this pointer (mptr) to the C# implementation of the interface. Also I'm not sure how to declare the interface CAPIInterface in C# as well. I tried declaring the interface this way:

[StructLayout(LayoutKind.Sequential)]
public class CAPIInterface
{
    public delegate int Release();
    public delegate string ErrorDescription(int code);
    public delegate int Login(int login, string password);
}

But then it doesn't compile... it returns this error: Error 3 Non-invocable member 'CAPIInterface.Login' cannot be used like a method. I understand that the delegates must be instantiated somewhere as well... but how to do it? Is it correct approach at all to declare the CAPIInterface as above?

I was able to convert my C++ API to C# with the help of SWIG. It works great. Thank you.

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