【问题标题】:How to call class ref object in c unmanaged dll from c#如何从 c# 调用 c 非托管 dll 中的类 ref 对象
【发布时间】:2013-01-20 04:08:09
【问题描述】:

我正在尝试调用 c++ 未管理的 dll ref。来自 c# 应用程序的类对象。使用 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 函数?

【问题讨论】:

    标签: c# c++ visual-c++ unmanaged


    【解决方案1】:

    这是完整的代码吗?我对此表示怀疑,因为您甚至在 CDeskApiCallback 中没有任何方法(这可能是一些用于回调的类接口类)。无论哪种方式,C++“回调”对象与 .NET 委托非常不同,这就是您尝试使用它的方式。

    另一个主要缺陷是您试图通过 dll 导入 C++ 方法 (CDeskApi::Initialise)。该部分可以正常工作,但是您将如何实例化 C++ 类以便可以对其调用 Initialise?

    我相信您可以通过某种方式开始使用 P/Invoke,但为此目的,COM 或 C++/CLI 会更好。任何 COM 或 C++/CLI 类和接口都将直接对 C# 可见,而无需在 C# 代码中编写奇怪的编组指令。

    【讨论】:

    • 是的。你是对的。在我脑海里。但我对 c++/CLI 不太了解,所以你能提供任何链接或示例。谢谢
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2011-03-04
    • 2011-02-06
    • 2011-05-22
    相关资源
    最近更新 更多