2010-03-18 91 views
17

是否可以調用C(++)靜態函數指針(不是委託)這樣調用C++函數指針從C#

typedef int (*MyCppFunc)(void* SomeObject); 

從C#?

void CallFromCSharp(MyCppFunc funcptr, IntPtr param) 
{ 
    funcptr(param); 
} 

我需要能夠從c#回調到一些舊的C++類。 C++被管理,但類不是引用類(還)。

到目前爲止,我不知道如何從c#中調用C++函數指針,有可能嗎?

+0

我認爲最好的方法是創建一個C++/CLI包裝爲。 – Anzurio 2010-03-18 15:26:32

+0

這工作對我來說,https://stackoverflow.com/questions/39790977/how-to-pass-a-delegate-or-function-pointer-from-c-sharp-to-c-and-call-it- 39803574#39803574 – 2017-11-09 07:30:05

回答

16

dtb是正確的。這裏有一個更詳細的Marshal.GetDelegateForFunctionPointer的例子。它應該適合你。

在C++:

static int __stdcall SomeFunction(void* someObject, void* someParam) 
{ 
    CSomeClass* o = (CSomeClass*)someObject; 
    return o->MemberFunction(someParam); 
} 

int main() 
{ 
    CSomeClass o; 
    void* p = 0; 
    CSharp::Function(System::IntPtr(SomeFunction), System::IntPtr(&o), System::IntPtr(p)); 
} 

在C#:

public class CSharp 
{ 
    delegate int CFuncDelegate(IntPtr Obj, IntPtr Arg); 
    public static void Function(IntPtr CFunc, IntPtr Obj, IntPtr Arg) 
    { 
    CFuncDelegate func = (CFuncDelegate)Marshal.GetDelegateForFunctionPointer(CFunc, typeof(CFuncDelegate)); 
    int rc = func(Obj, Arg); 
    } 
} 
2

看看Marshal.GetDelegateForFunctionPointer方法。

delegate void MyCppFunc(IntPtr someObject); 

MyCppFunc csharpfuncptr = 
    (MyCppFunc)Marshal.GetDelegateForFunctionPointer(funcptr, typeof(MyCppFunc)); 

csharpfuncptr(param); 

,我不知道這是否真的與你的C++方法可行,但正如MSDN文檔指出:

您不能使用此方法,通過C++

獲得函數指針
+1

描述說:「你不能使用這個方法通過C++獲得函數指針」 - 可悲的是,我的函數指針是一個C++指針。 – Sam 2010-03-18 14:27:37

+1

然後,我想你的唯一選擇是在C++庫中爲C++創建託管(ref)包裝類。 – dtb 2010-03-18 14:30:46