C# Return DllExport 接口

C# Return Interface by DllExport

我正在尝试 return 关于数据加密的界面 来自 RobertGiesecke UnmanagedExports 的 C# 方法

这是我的代码:

    public class Crypter : ICrypter
    {

    public bool Encrypt(IntPtr data)
    {
        /* Sorry I Can't Show How I Do This */

        Marshal.Copy(encdata, 0, data, encdata.Length);

        return true;
    }

    public bool Decrypt(IntPtr data)
    {
        /* Sorry I Can't Show How I Do This */

        return true;
    }
}

public interface ICrypter
{
    bool Encrypt(IntPtr data);
    bool Decrypt(IntPtr data);
}

我导出的函数:

    [DllExport("CreateCrypter", CallingConvention.Cdecl)]
    public static ICrypter CreateCrypter()
    {
        return new Crypter();
    }

在 C++ 部分:

class ICrypter
{
 public:
    virtual int testFunc1();
    virtual int testFunc2();
 private:

};

这里是 Wrapper

typedef ICrypter*(*CreateCrypter)();

HMODULE mylib = LoadLibrary(L"C:\Users\Moien\Documents\Visual Studio 2013\Projects\UnmanagedInterfaces\MyLibrary\bin\Debug\MyLibrary.dll");

在该代码之后,我使用 GetProcAddress 并测试我的添加函数以确保我的函数已导出,但我调用了 CreateCrypter 并且我的程序崩溃了

Solved by help from (http://code4k.blogspot.ae/2010/10/implementing-unmanaged-c-interface.html)

    public static IntPtr GetInterfacePointer(Delegate[] functions)
    {
        // Allocate object layout in memory 
        // - pointer to VTBL table
        // - following that the VTBL itself - count of functions
        IntPtr nativePointer = Marshal.AllocHGlobal(IntPtr.Size * (1 + functions.Count()));

        // virtual table
        IntPtr vtblPtr = IntPtr.Add(nativePointer, IntPtr.Size);

        Marshal.WriteIntPtr(nativePointer, vtblPtr);

        for (int i = 0; i < functions.Count(); i++)
        {
            Marshal.WriteIntPtr(IntPtr.Add(vtblPtr, IntPtr.Size * i),
                Marshal.GetFunctionPointerForDelegate(functions[i]));
        }

        return nativePointer;
    }

在 (http://code4k.blogspot.ae/2010/10/implementing-unmanaged-c-interface.html)

的帮助下解决了
public static IntPtr GetInterfacePointer(Delegate[] functions)
{
    // Allocate object layout in memory 
    // - pointer to VTBL table
    // - following that the VTBL itself - count of functions
    IntPtr nativePointer = Marshal.AllocHGlobal(IntPtr.Size * (1 + functions.Count()));

    // virtual table
    IntPtr vtblPtr = IntPtr.Add(nativePointer, IntPtr.Size);

    Marshal.WriteIntPtr(nativePointer, vtblPtr);

    for (int i = 0; i < functions.Count(); i++)
    {
        Marshal.WriteIntPtr(IntPtr.Add(vtblPtr, IntPtr.Size * i),
            Marshal.GetFunctionPointerForDelegate(functions[i]));
    }

    return nativePointer;
}