将方法指针从 C# 传递到 Delphi DLL
我在将字符串作为 PChar 传递到 Delphi 构建的 DLL 时遇到了一些问题,感谢 Jens Mühlenhoff 解决了它。
现在我有另一个问题 -
如果 Delphi 声明是常规类型过程,则在传递给 DLL 时我已成功回调 c# 方法,但如果 Delphi 声明是方法类型过程,我会收到“尝试读取或写入受保护的内存”错误。
我尝试搜索...
这是 Delphi 声明
TCallBack = procedure ( s : String) of object;stdcall;
C# 代码
[DllImport(
"DLLTest.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi,
EntryPoint = "DLL_Test"
)]
public static extern void DLL_Test(IntPtr p, [MarshalAs(UnmanagedType.LPStr)] string Location, int AIntValue);
public delegate void MethodCallBackEvent(string s);
public event MethodCallBackEvent Info;
public void GetInfo(string s)
{
MessageBox.Show("Info: " + s);
}
这是用作的
Info = GetInfo; //or Info = new MethodCallBackEvent(GetInfo);
IntPtr p = Marshal.GetFunctionPointerForDelegate(Info);
DLL_Test(p, "location message", 10);
I've had some problems passing string as PChar to Delphi built DLL, and resolved it thanks to Jens Mühlenhoff.
Now I have another issue -
I've made successful callback of c# method when passed to DLL if the Delphi declaration is a regular type procedure, but if Delphi declaration is a method type procedure I get "Attempted to read or write protected memory" error.
I tried searching...
Here is Delphi declaration
TCallBack = procedure ( s : String) of object;stdcall;
Here is C# code
[DllImport(
"DLLTest.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi,
EntryPoint = "DLL_Test"
)]
public static extern void DLL_Test(IntPtr p, [MarshalAs(UnmanagedType.LPStr)] string Location, int AIntValue);
public delegate void MethodCallBackEvent(string s);
public event MethodCallBackEvent Info;
public void GetInfo(string s)
{
MessageBox.Show("Info: " + s);
}
used as
Info = GetInfo; //or Info = new MethodCallBackEvent(GetInfo);
IntPtr p = Marshal.GetFunctionPointerForDelegate(Info);
DLL_Test(p, "location message", 10);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个工作示例。 DllTest1 使用普通函数回调。 DllTest2 期望回调作为直接的 C# 函数指针(需要在 Delphi 端进行一些小修改),DllTest3 期望一个 Delphi 方法回调指针(需要在 C# 端进行一些小修改)。
Here is a working example. DllTest1 is using a normal function callback. DllTest2 expects the callback as a direct C# function pointer (requires a small hack on the Delphi side), and DllTest3 expects a Delphi method callback pointer (requires a small hack on the C# side).