Tag: callback

如何使用pinvoke使用cdecl回调

我有一个具有cdecl回调的ac库。 我如何从c#中使用这些。 一切似乎都说他们必须是stdcall回调 要清楚: delegate int del(); [dllimport(“mylib.dll”,CallingConvention=CallingConvention.Cdecl)] public static extern int funcwithcallback(del foo); 其中del必须被称为cdecl-wise

C#字符串编组和LocalAlloc

我有一个来自非托管DLL的COM回调,我需要在C#中使用它。 非托管DLL期望被调用者使用LocalAlloc (调用者将使用LocalFree )分配内存,使用WSTR填充它并分别设置value和chars到WSTR指针和字符串长度。 代码片段我正在尝试转换为C#: STDMETHODIMP CMyImpl::GetString(LPCSTR field, LPWSTR* value, int* chars) { CStringW ret; if (!strcmp(field, “matrix”)) { ret = L”None”; if (…) ret.Append(L”001″); else if (…) ret.Append(L”002″); else ret.Append(L”003″); } if (!ret.IsEmpty()) { int len = ret.GetLength(); size_t sz = (len + 1) * sizeof(WCHAR); LPWSTR buf = (LPWSTR)LocalAlloc(LPTR, sz); if (!buf) { […]

如何获取在回调中传递给异步方法的参数

我需要一个传递给CallbackMethodSendRegistration中的AsyncSendRegistrationMethod的Label。 private delegate ResponceFromServer AsyncSendRegistrationDelegate(RegistrationToUser registrationToUser, Label label); private ResponceFromServer AsyncSendRegistrationMethod(RegistrationToUser registrationToUser, Label label) { SetText(label, registrationToUser.Name + ” registration…”); return Requests.DataBase.Authorization.Registration( registrationToUser.Name, registrationToUser.IdRoleUser, registrationToUser.IdGroup); } private void CallbackMethodSendRegistration(IAsyncResult ar) { var sendRegistrationDelegate = (AsyncSendRegistrationDelegate)ar.AsyncState; var responceFromServer = (ResponceFromServer)sendRegistrationDelegate.EndInvoke(ar); if(responceFromServer.IsError) { //here need label.Text } else { } }

从C ++传递一个函数指针,由C#调用 – 函数的参数包括一个宽字符串(LPCWSTR)

我正在编写一个C#库供本机C ++应用程序使用。 我使用C ++ / CLI作为互操作性机制。 我需要将回调函数从C ++传递给C#(使用C ++ / CLI作为中间层)。 C#库需要使用零终止的宽字符串来调用C ++函数; 即回调函数的原型是 Func(LPCWSTR pszString); 还有其他参数,但它们对于这个讨论并不重要。 我搜索网,发现Marshal.GetDelegateForFunctionPointer方法,我可以使用。 这个问题是它将System.String从C#转换为char *而不是我正在寻找的wchar_t *。 此外,如果可能的话,实现此代码示例的最佳方法是什么,包括C ++ / CLI部分。 C ++ / CLI dll依赖于C#dll。 方法需要同步调用。

通过Interop / pinvoke传递C#回调函数

我正在编写一个C#应用程序,它使用Interop服务来访问本机C ++ DLL中的函数。 我已经使用了大约10种不同的function。 现在我不知道如何处理将回调作为参数传递,以便DLL可以调用我的代码。 这是DLL的函数原型: typedef void (WINAPI * lpfnFunc)(const char *arg1, const char *arg2) 并且允许我传递上述类型的函数: int WINAPI SetFunc(lpfnFunc f) 这是委托和函数定义的C#代码: public delegate void Func(string arg1, string arg2); public static void MyFunc(string arg1, string arg2) 这是我的SetFunc Interop函数的C#代码: [DllImport(“lib.dll”, CharSet = CharSet.Ansi)] public static extern int SetFunc(Func lpfn); 最后这里是我调用SetFunc函数并将其传递给我的回调的代码: SetFunc(new Func(MyFunc)); 不幸的是,我的function应该被调用。 SetFunc函数的返回值是返回Success的错误代码,所以要么它没有调用我的函数,要么因为我的代码错误而无法正常工作。