You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用参数为int、返回string的Delphi DLL函数的问题及解决方法

问题描述

现有一个使用Delphi编写的DLL,其中一个函数入参为int类型(Delphi中为Integer),返回值为string类型(Delphi中为PWideChar)。该DLL的文档提供的细节很少,确认DLL本身没有问题,在Python中可以通过设置restype成功调用该函数,示例代码如下:

DLLName.FunctionName.restype = c_wchar_p 

在C# 5.0中调用该函数时,若将返回值设置为sbyte、int、long等数值类型时能得到返回内容,若设置为string类型则会报错,初始声明代码如下:

[DllImport(dll_path, CallingConvention = CallingConvention.StdCall)]
    public static extern sbyte GetNameByID(int nID);

第一次调用尝试如下:

public static string GetName()
    {   
       string result = GetNameByID(1);
       return result;
    }

试过用.ToString()或者(string)强转结果,均未成功。

解决方案

该函数实际返回的是指针,因此需要对DllImport声明做如下修改:

[DllImport(dll_path, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr GetNameByID(int nID);

处理返回值时,将指针编组为Unicode字符串即可,调用代码如下:

public static string GetName()
    {   
       string result = Marshal.PtrToStringUni(GetNameByID(1));
       return result;
    }

内容的提问来源于stack exchange,提问作者roccaforte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:06:08