將 C++ 函數指針設置為 C# 委託 (set C++ function pointer as C# delegate)


問題描述

將 C++ 函數指針設置為 C# 委託 (set C++ function pointer as C# delegate)

I have a unmanaged c++ application as COM client and a C# COM server. now i want COM server can invoke a c++ function.

C# :

[ClassInterface(ClassInterfaceType.AutoDual)]
public class SomeType
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void DeleCallBack(string info);
    public DeleCallBack CallBack;
    public void  SetCallBack(ref IntPtr ptr)
    {
        CallBack = (DeleCallBack)Marshal.GetDelegateForFunctionPointer(ptr, typeof(DeleCallBack));
    }
}

C++:

HRESULT hr = E_FAIL;
CComPtr<WindowsFormsApplicationVC9::_SomeType> spTmp;
hr = spTmp.CoCreateInstance(__uuidof(WindowsFormsApplicationVC9::SomeType));
if (SUCCEEDED(hr))
{
    spTmp->SetCallBack(OnCallBack);
}
void  OnCallBack(BSTR info)
{
    // c++ function call...;
}

I'm not sure it is the right way to just pass the OnCallBack function pointer to SetCallBack. I noticed that some sample of calling GetDelegateForFunctionPointer should GetProcessAddress to get the function pointer address, but i can't do that since there are may be different c++ COM client with different function name.

any suggestion?


參考解法

方法 1:

One way to do it is to expose your C++ functions via __declspec(dllexport), then simply write P/Invoke for those functions. Now you can use those P/Invoke functions as delegates.

Deep down this is essentially the GetProcAddress approach but the C# compiler makes it syntactically nicer for you.

(by ArdenZhaokizzx2)

參考文件

  1. set C++ function pointer as C# delegate (CC BY-SA 3.0/4.0)

#Callback #C++ #C# #com-interop






相關問題

將 C++ 函數指針設置為 C# 委託 (set C++ function pointer as C# delegate)

YouTube(注入)視頻結束回調 (YouTube (injected) video ends callback)

我如何在 Rails 中“驗證”銷毀 (How do I 'validate' on destroy in rails)

Як я магу рэалізаваць зваротныя выклікі на іншы сервер у C# (How can I implement callbacks to another server in c#)

顯示等待通知,直到回調從線程返回 (Show waiting notification till callback returns from thread)

應用程序未通過文本服務框架 DLL 檢測輸入語言更改 (Application not detecting input language changes via Text Service Framework DLL)

回調參數名稱 (Callback parameters name)

我是否以正確的方式考慮回調? (Am I thinking about Callbacks the right way?)

MSMQ 異步異常行為 - .NET 4.0 與 .NET 2.0 (MSMQ asynchronous exception behavior - .NET 4.0 vs .NET 2.0)

參數連接問題。我該如何處理 (parameter connection problem. How can I deal with this)

如何在 JavaScript 中實現動態回調參數 (How can I achieve dynamic callback arguments in JavaScript)

回調警告:回調錯誤創建破折號數據表 (Callback warning: Callback error creating dash' DataTable)







留言討論