我试图将字符串从C#传递给Delphi内置的DLL。Delphi DLL需要PChar。
这是Delphi的出口
procedure DLL_Message(Location:PChar;AIntValue :integer);stdcall;
external 'DLLTest.dll';
Run Code Online (Sandbox Code Playgroud)
C#导入(我尝试的最后一个,有字符串,char * ref字符串...)
[DllImport(
"DLLTest.dll",
CallingConvention = CallingConvention.StdCall,
CharSet = CharSet.Ansi,
EntryPoint = "DLL_Message"
)]
public static extern void DLL_Message(IntPtr Location, int AIntValue);
Run Code Online (Sandbox Code Playgroud)
我以任何方式获得访问冲突访问值。
有什么解决方案可以在C#中将字符串值作为PChar传递?
我有一些问题,将字符串作为PChar传递给Delphi构建的DLL,并且由于JensMühlenhoff解决了它.
现在我有另一个问题 -
如果Delphi声明是常规类型过程,我在传递给DLL时成功回调了c#方法,但如果Delphi声明是一个方法类型过程,我会"尝试读取或写入受保护的内存"错误.
我试着搜索......
这是Delphi声明
TCallBack = procedure ( s : String) of object;stdcall;
Run Code Online (Sandbox Code Playgroud)
这是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);
}
Run Code Online (Sandbox Code Playgroud)
用作
Info = GetInfo; //or Info = new MethodCallBackEvent(GetInfo);
IntPtr p = Marshal.GetFunctionPointerForDelegate(Info);
DLL_Test(p, "location message", 10);
Run Code Online (Sandbox Code Playgroud)