簡體   English   中英

如何從C#調用C非托管DLL中的類ref對象

[英]How to call class ref object in c unmanaged dll from c#

我正在嘗試調用C ++ umnamanged dll ref。 C#應用程序中的class對象。 與VC ++一起使用的DLL函數調用。

我的VC ++代碼如下

class  METHOD_TYPE CDeskApi
{
public:
    CDeskApi(void);

        /*
    Description : Initiates a connection to NEST system
    Parameters  : 1. serialkey provided to implement the api
                  2. object of CDeskApiCallback implemented

    Return      : 0 in case of success and -1 in case of error  
        */  
    int Initialise(char *serialkey, CDeskApiCallback* callback);
        /*
        Description : Request data from the server
        Parameters  : 1. symbol of interest
                      2. intervals of 1 min, multiples of 1 min, DAILY_PERIOD in case of daily.
                      3. data to be retrieved from. in no of seconds since epoch
                      4. identifier, which is returned in the callback          
        Return      : 0 in case of success and -1 in case of error  
        */      

    ~CDeskApi(void);
};

class METHOD_TYPE CDeskApiCallback    
{
public:    
};


class Myhandler : public CDeskApiCallback    
{    
public:

    virtual int quote_notify( const char* symbol, int size, Quotation *pQuotes, unsigned long echo)
    {
        return 0;    
    };    
};

Myhandler handler;

void Cnest_desk_appDlg::OnBnClickedOk()    
{    
    if(odesk.Initialise("VWAP", &handler))    
    {    
        AfxMessageBox("Error!");

        return;//error
    }    
}

我的C#代碼如下

[DllImport("DeskApi.dll", EntryPoint = "?Initialise@CDeskApi@@QAEHPADPAVCDeskApiCallback@@@Z")]
static extern void DeskApiInitialize(IntPtr symbol, callback fn);

private delegate int callback(IntPtr symbol, int nMaxSize, ref Quotation pQuotes, ulong echo);

private callback mInstance;

private void btnFetch_Click(object sender, EventArgs e)
{
    IntPtr ptrCString = (IntPtr)Marshal.StringToHGlobalAnsi(txtFetch.Text);

    CallTest.DeskApiGetQuote(ptrCString,quote_notify);

    Marshal.FreeHGlobal(ptrCString);    
}

private int quote_notify(IntPtr symbol, int nMaxSize, ref Quotation pQuotes, ulong echo)
{
    return 0;    
}

在C#中,一切正常,但是不調用quote_notify函數嗎?

那是完整的代碼嗎? 我對此表示懷疑,因為您甚至在CDeskApiCallback中都沒有任何方法(這大概是一些用於回調的類接口類)。 無論哪種方式,C ++“回調”對象都與.NET委托有很大的不同,這就是您嘗試使用它的方式。

另一個主要缺陷是您正在嘗試dll導入C ++方法(CDeskApi :: Initialise)。 該部分可以正常工作,但是如何實例化C ++類,以便可以對其調用Initialize?

我確定您可以以某種方式使用P / Invoke,但是為此,COM或C ++ / CLI會更好。 任何COM或C ++ / CLI類和接口對於C#都是直接可見的,而不必在C#代碼中編寫怪異的編組指令。

暫無
暫無

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

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