[英]How to pass c# string to delphi .dll PChar type?
So I learned using IntPtr in this case, 所以我学会了在这种情况下使用IntPtr,
-delphi (delphi 2006 version) code -delphi(delphi 2006版本)代码
function GetRequestResult(out code:integer):PChar; stdcall;
begin
LogMessage('GetRequestResult');
code:=requestCode;
result:=PChar(RequestResult);
LogMessage('GetRequestResult done');
end;
then, for using in c#, I used like, 然后,在c#中使用时,
IntPtr str = GetRequestResult(out code);
string loginResult = Marshal.PtrToStringAnsi(str);
and this works well. 而且效果很好。
Then, how about this case? 那这种情况怎么样
-delphi code -delphi代码
procedure Login(login,password:PChar); stdcall;
...
...
this PChar is inside (). 此PChar位于()内部。 So what is exact way to pass string value to that Login delphi function? 那么将字符串值传递给该Login delphi函数的确切方法是什么?
[DllImport ("ServerTool")] [DllImport(“ ServerTool”)]
private static extern void Login([MarshalAs(UnmanagedType.LPStr)]string id, [MarshalAs(UnmanagedType.LPStr)]string pass); 私有静态外部无效登录([MarshalAs(UnmanagedType.LPStr)]字符串ID,[MarshalAs(UnmanagedType.LPStr)]字符串传递);
private static extern void Login(IntPtr id, IntPtr pass); 私有静态外部无效Login(IntPtr id,IntPtr pass); // in this case, how use this IntPtr in latter part? //在这种情况下,如何在后面的部分中使用此IntPtr?
private static extern void Login(string id, string pass); 私有静态外部无效登录(字符串ID,字符串传递);
Thanks in advance. 提前致谢。
Your option 3 is the correct way to do this. 您的选项3是执行此操作的正确方法。 The p/invoke marshaller will map a C# string to a pointer to null terminated character array, ie PChar. p /调用编组器将C#字符串映射到指向以空终止的字符数组(即PChar)的指针。 The default calling convention is stdcall, and the default character set is Ansi and so you don't need to specify those. 默认的调用约定为stdcall,默认的字符集为Ansi,因此您无需指定这些约定。
Your option 1 works also but is unnecessarily verbose since you are just re-stating the default marshalling. 您的选项1也可以使用,但是不必要地冗长,因为您只是在重新设置默认的编组。 Option 2 could work also but you'd just be creating extra work for yourself. 选项2也可以工作,但您只是为自己创建额外的工作。 You'd have the responsibility of freeing the IntPtr values once the native function call returned. 一旦本机函数调用返回,您将有责任释放IntPtr值。
You can use: Marshal.StringToHGlobalAnsi. 您可以使用:Marshal.StringToHGlobalAnsi。 http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.