如何从 DllImport 获取字符串数组

问题描述

我正在尝试从 dll 中获取字符串数组。

这是这个 dll 函数的文档。

Request_the_Value_of_ICT_multi_Currency_Bill_Validator()
(a)Input
1. strCurrecy: AnsiString
(b)Return:pData: AnsiString*
pData[0] Value1
pData[1] Value2
...
pData[19] Value3
(c)Example:
AnsiString *pData = 
Request_the_Value_of_ICT_multi_Currency_Bill_Validator("AUD");

我在下面试过这段代码,返回的是一些非英语语言

IntPtr pData = Request_the_Value_of_ICT_multi_Currency_Bill_Validator("AUD");
string stringB = Marshal.PtrToStringAnsi(pData);

string stringA = Marshal.PtrToStringUni(pData);

这是dll

[DllImport("ps3_DLL.dll",EntryPoint = "Request_the_Value_of_ICT_multi_Currency_Bill_Validator",CharSet = CharSet.Unicode,CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr Request_the_Value_of_ICT_multi_Currency_Bill_Validator(string strCurrency);

这是我反汇编dll得到的函数。我真的不知道这是什么意思

This is the function i got from dis

更新:我终于得到了正确的代码

 IntPtr pData = ictdll.Request_the_Country_code_of_ICT_multi_Currency_BA();

        IntPtr[] pGetData = new IntPtr[9];
        Marshal.copy(pData,pGetData,pGetData.Length);

        string[] currency = new string[9];

        for (int i = 0; i < 9; i++)
        {
            currency[i] = Marshal.PtrToStringAnsi(pGetData[i]);
        }

解决方法

您提供的文档明确指出 Ansi。此外,这看起来是一个字符串指针的数组,因此您需要编组整个数组。

不清楚谁应该释放所有这些内存,您可能需要调查一下。

[DllImport("PS3_DLL.dll",CharSet = CharSet.Ansi,CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr[] Request_the_Value_of_ICT_multi_Currency_Bill_Validator
    (string strCurrency);
var arrPtr = Request_the_Value_of_ICT_multi_Currency_Bill_Validator
    (yourCurrency);

arrayOfStrings = arrPtr.Select(ptr =>
    Marshal.PtrToStringAnsi(ptr)).ToArray()

我建议您检查调用约定是否正确。 Windows API 使用 StdCall,但大多数 C 库使用 CDecl

,

浏览了很多天,我终于得到了正确的代码!

    IntPtr pData = ictdll.Request_the_Country_code_of_ICT_multi_Currency_BA();

    IntPtr[] pGetData = new IntPtr[9];
    Marshal.Copy(pData,pGetData,pGetData.Length);

    string[] currency = new string[9];

    for (int i = 0; i < 9; i++)
    {
        currency[i] = Marshal.PtrToStringAnsi(pGetData[i]);
    }