如何调用从C#这德尔福的.dll功能? [英] How to call this delphi .dll function from C#?

查看:132
本文介绍了如何调用从C#这德尔福的.dll功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Delphi代码(DELPHI版本:涡轮德尔福资源管理器(这是2006年德尔福))

// delphi code (delphi version : Turbo Delphi Explorer (it's Delphi 2006))

function GetLoginResult:PChar;
   begin
    result:=PChar(LoginResult);
   end; 



// C#代码使用上述德尔福功能(我使用unity3d内,C#)

//C# code to use above delphi function (I am using unity3d, within, C#)

[DllImport ("ServerTool")]
private static extern string GetLoginResult();  // this does not work (make crash unity editor)

[DllImport ("ServerTool")] 
[MarshalAs(UnmanagedType.LPStr)] private static extern string GetLoginResult(); // this also occur errors



什么是使用该功能在C#中正确的方式?

What is right way to use that function in C#?

(用于在Delphi中也使用,代码是这样,
如果(事件= 1)和(标签= 10),那么writeln('登录结果:',GetLoginResult) ;)

(for use in also in delp code is like, if (event=1) and (tag=10) then writeln('Login result: ',GetLoginResult); )

推荐答案

该内存是由您的Delphi代码所拥有的字符串,但您的p / Invoke的代码将导致编组调用 CoTaskMemFree 上内存。

The memory for the string is owned by your Delphi code but your p/invoke code will result in the marshaller calling CoTaskMemFree on that memory.

您需要做的就是告诉编组,它不应该采取释放内存的责任。

What you need to do is to tell the marshaller that it should not take responsibility for freeing the memory.

[DllImport ("ServerTool")] 
private static extern IntPtr GetLoginResult();



然后使用 Marshal.PtrToStringAnsi()来。返回的值转换为C#字符串

Then use Marshal.PtrToStringAnsi() to convert the returned value to a C# string.

IntPtr str = GetLoginResult();
string loginResult = Marshal.PtrToStringAnsi(str);

您也应该确保调用约定比赛通过声明Delphi函数是 STDCALL

You should also make sure that the calling conventions match by declaring the Delphi function to be stdcall:

function GetLoginResult: PChar; stdcall;



虽然恰巧这个调用约定不匹配不会为一个没有功能关系参数和指针大小的返回值。

Although it so happens that this calling convention mis-match doesn't matter for a function that has no parameters and a pointer sized return value.

为了这一切的工作,德尔福字符串变量 LoginResult 有是一个全局变量,以便其内容是 GetLoginResult 返回后有效。

In order for all this to work, the Delphi string variable LoginResult has to be a global variable so that its contents are valid after GetLoginResult returns.

这篇关于如何调用从C#这德尔福的.dll功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆