[英]How do I call the ExtEscape with PASSTRHOUGH function from c#?
[英]How do I call a c function from C#
我想在C#中使用這個C函數:
typedef void (*WRITE_CALLBACK)(int hMountEnv, unsigned __int64 NumBytesWritten,
void* pContext);
我如何定義它以便我可以調用它?
我需要做任何其他事情才能使這項工作成功嗎?
有關如何編組函數指針的信息,請查看http://msdn.microsoft.com/en-us/library/ektebyzx(v=vs.80).aspx 。 該頁面底部有一個示例。
我會為你做C#,因為我不知道指針的方向,我會同時展示。 對於涉及調用約定的問題,有一些問題可能會有問題。 Marshal.GetDelegateForFunctionPointer
和Marshal.GetFunctionPointerForDelegate
假設函數指針將是StdCall,所以如果你不能訪問非托管庫以確保函數指針是標准調用(我認為C默認為cdecl),你必須創建一個非托管的填充程序庫來更改調用約定,除非有其他我不知道的方法。
這將是我命名為“UnmanagedLib.dll”的C DLL的標題。
typedef void ( __stdcall *WRITE_CALLBACK)(int hMountEnv, unsigned __int64 NumBytesWritten, void* pContext);
extern "C" {
__declspec(dllexport) WRITE_CALLBACK __stdcall FunctionProducingFunctionPointer(void);
__declspec(dllexport) void __stdcall FunctionConsumingFunctionPointer(WRITE_CALLBACK callback);
}
這將是DLL的CPP文件。
#include "UnmanagedLib.h"
void __stdcall SampleFunction(int hMountEnv, unsigned __int64 NumBytesWritten, void* pContext)
{
}
WRITE_CALLBACK __stdcall FunctionProducingFunctionPointer(void)
{
return &SampleFunction;
}
void __stdcall FunctionConsumingFunctionPointer(WRITE_CALLBACK callback)
{
// sample call
(*callback)(0,0,NULL);
}
最后,這是一個使用DLL的C#程序。
class Program
{
public delegate void WRITE_CALLBACK(int hMountEnv, ulong NumBytesWritten, IntPtr pContext);
[DllImport("UnmanagedLib.dll")]
public static extern IntPtr FunctionProducingFunctionPointer();
[DllImport("UnmanagedLib.dll")]
public static extern void FunctionConsumingFunctionPointer(IntPtr functionPointer);
public static void SampleFunction(int hMountEnv, ulong NumBytesWritten, IntPtr pContext)
{
}
static void Main(string[] args)
{
var functionDelegateToManagedSampleFunction = new WRITE_CALLBACK(SampleFunction);
var functionDelegateToUnmanagedSampleFunction = Marshal.GetDelegateForFunctionPointer(FunctionProducingFunctionPointer(), typeof(WRITE_CALLBACK));
// call the unmanaged sample function via its pointer
functionDelegateToUnmanagedSampleFunction.DynamicInvoke(new object[] {0,0ul,null});
// pass the managed sample function to the unmanaged code
FunctionConsumingFunctionPointer(Marshal.GetFunctionPointerForDelegate(functionDelegateToManagedSampleFunction));
}
}
這看起來像是一個委托而不是一個函數/方法本身。 你不會這稱呼它,它將作為一個函數指針提供給其他東西。 等價物可能是這樣的:
public delegate void WRITE_CALLBACK(int hMountEnv, uint numBytesWritten, object pContext);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.