簡體   English   中英

如何通過C#從C ++ dll調用struct中的函數

[英]How to call a function in struct from C++ dll by C#

我的C#項目必須引用一個C ++ dll,

struct中的SetConfig()是我的目標,頭部看起來像

extern "C"
{
    int HSAPI GetSDKVersion();
    IHsFutuComm* HSAPI NewFuCommObj(void* lpReserved = NULL);

    struct IHsFutuComm:public IHSKnown
    {
        virtual int HSAPI SetConfig(const char* szSection,const char* szName,const char* szVal) = 0;
        ...
    }
}

和C#看起來像

class Program
{
    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string dllToLoad);

    [DllImport("kernel32.dll")]
    public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);

    public delegate Int32 GetSDKVersion();
    public delegate IntPtr NewFuCommObj(IntPtr lpReserved);

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
    public struct IHsFutuComm
    {
        [MarshalAs(UnmanagedType.FunctionPtr)]
        public SetConfig pSetConfig;
    }

    [UnmanagedFunctionPointer(CallingConvention.StdCall)]
    public delegate Int32 SetConfig(string szSection, string szName, string szVal);

    static void Main(string[] args)
    {
        var pDll = LoadLibrary("HsFutuSDK.dll");
        var pGetSDKVersion = GetProcAddress(pDll, "GetSDKVersion");
        var dGetSDKVersion = (GetSDKVersion)Marshal.GetDelegateForFunctionPointer(pGetSDKVersion, typeof(GetSDKVersion));
        var sdkVersion = dGetSDKVersion();
        if (sdkVersion == 0x10000019)
        {
            var pNewFuCommObj = GetProcAddress(pDll, "NewFuCommObj");
            var dNewFuCommObj = Marshal.GetDelegateForFunctionPointer(pNewFuCommObj, typeof(NewFuCommObj)) as NewFuCommObj;
            var pIHsFutuComm = dNewFuCommObj(IntPtr.Zero);
            var IHsFutuComm1 = (IHsFutuComm)Marshal.PtrToStructure(pIHsFutuComm, typeof(IHsFutuComm));

            //error here
            var re = IHsFutuComm1.pSetConfig("futu", "server", "127.0.0.1:2800");
        }
    }
}

最后一行的錯誤是“試圖讀取或寫入受保護的內存。這通常表明其他內存已損壞。”

如何通過C#調用SetConfig()?

在此SetConfig中,是結構的(純)虛擬成員函數,因此調用約定應為thiscall ,並且函數指針不像C#代碼中那樣保留在結構中,而是位於vtable中。

C ++代碼中的結構聲明可能更像C#中的接口,而不是C#中的結構。

抱歉,我無法提供完整的答案,但我希望這會為您指明正確的方向。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM