问题描述
我写它使用互操作的服务来访问功能于一身的本地C ++ DLL C#应用程序。我已经使用这些工作大约10个不同的功能。
I am writing a C# application which uses Interop services to access functions in a native C++ DLL. I am already using about 10 different functions which are working.
现在我不知道如何处理传递一个回调作为参数,以便该DLL可以调用我的code。
Now I am not sure how to handle passing a callback as a parameter so that the DLL can call my code.
下面是DLL的函数原型:
Here is the function prototype of the DLL:
typedef void (WINAPI * lpfnFunc)(const char *arg1, const char *arg2)
和,让我通过上述类型的功能:
And the function that allows me to pass the above type:
int WINAPI SetFunc(lpfnFunc f)
下面是我的C#code的委托和函数定义:
Here is my C# code for the delegate and function definitions:
public delegate void Func(string arg1, string arg2);
public static void MyFunc(string arg1, string arg2)
下面是我的C#code为SetFunc互操作功能:
Here is my C# code for the SetFunc Interop function:
[DllImport("lib.dll", CharSet = CharSet.Ansi)]
public static extern int SetFunc(Func lpfn);
和终于在这里是code,其中我所说的SetFunc功能,通过它我的回调:
And finally here is the code where I call the SetFunc function and pass it my callback:
SetFunc(new Func(MyFunc));
不幸的是我的函数没有被调用时是应该的。在SetFunc函数的返回值返回错误code代表成功的,所以要么它不叫我的功能,或者它不工作,因为我的code是错误的。
Unfortunately my function is not being called when it should be. The return value of the SetFunc function is returning the error code for a Success, so either it's not calling my function or it's not working because my code is wrong.
推荐答案
这对我的作品:
Calc.h(Calc.dll,C ++):
Calc.h (Calc.dll, C++):
extern "C" __declspec(dllexport) double Calc(double x, double y, double __stdcall p(double, double));
Calc.cpp(Calc.dll,C ++):
Calc.cpp (Calc.dll, C++):
#include "calc.h"
__declspec(dllimport) double Calc(double x, double y, double __stdcall p(double, double))
{
double s = p(x*x, y*y);
return x * y + s;
}
的Program.cs(SAMPLE.EXE,C#):
Program.cs (Sample.exe, C#):
class Program
{
delegate double MyCallback(double x, double y);
[DllImport("Calc.dll", CallingConvention = CallingConvention.Cdecl)]
static extern double Calc(double x, double y, [MarshalAs(UnmanagedType.FunctionPtr)]MyCallback func);
static void Main(string[] args)
{
double z = Calc(1, 2, (x, y) => 45);
}
}
这篇关于通过互操作性/ PInvoke的传递一个C#回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!