【问题标题】:Receive char ** from a C++ DLL into C# string[]从 C++ DLL 接收 char ** 到 C# string[]
【发布时间】:2018-02-09 06:14:14
【问题描述】:

尽管有这么多问题,我还是找不到合适的答案。

我的目标是使用返回 char** 的 DLL 填充 string[]

DLL 声明

extern "C" SHTSDK_EXPORT int GetPeerList(SHTSDK::Camera *camera, int* id, int id_size, char** name, int name_size, int* statut, int statut_size);

我的导入

[DllImport(libName)]
static public extern int GetPeerList(IntPtr camera, IntPtr id, int id_size, IntPtr name, int name_size, IntPtr statut, int statut_size);

我在 C# 代码中的使用

StringBuilder[] name = new StringBuilder[nbPeer];
for (int i = 0; i < nbPeer; i++)
{
     name[i] = new StringBuilder(256);
}
//Alloc peer name array
GCHandle nameHandle = GCHandle.Alloc(name, GCHandleType.Pinned);
IntPtr pointeurName = nameHandle.AddrOfPinnedObject();

int notNewConnection = APIServices.GetPeerList(cameraStreaming, pointeurId, 

nbPeer, pointeurName, nbPeer, pointeurStatut, nbPeer);

// Now I'm supposed to read string with name[i] but it crashes

我错过了什么?我真的搜索了其他主题,我认为this one 可以工作,但仍然崩溃。

谢谢。

【问题讨论】:

  • 我建议制作一个混合程序集(带有 cli 支持的可视化 C++)并将其用作本机 (C++) 函数的包装器。这比您现在所做的要容易得多。
  • 也许会有所帮助? stackoverflow.com/questions/11508260/…

标签: c# c++ arrays string dll


【解决方案1】:

我建议您开发一个小型 C++/CLI 桥接 层。这个 C++/CLI 桥的目的是将 DLL 以 char** 原始指针的形式返回的字符串数组,并将其转换为 .NET 字符串数组,可以在 C# 代码中作为简单的 @ 使用987654323@.

C#string[](字符串数组)的 C++/CLI 版本是array&lt;String^&gt;^,例如:

array<String^>^ managedStringArray = gcnew array<String^>(count);

您可以使用operator[] 的常用语法(即managedStringArray[index])将每个字符串分配给数组。

你可以这样写一些代码:

// C++/CLI wrapper around your C++ native DLL
ref class YourDllWrapper
{
public:
    // Wrap the call to the function of your native C++ DLL,
    // and return the string array using the .NET managed array type
    array<String^>^ GetPeerList( /* parameters ... */ )
    {
        // C++ code that calls your DLL function, and gets
        // the string array from the DLL.
        // ...

        // Build a .NET string array and fill it with
        // the strings returned from the native DLL 
        array<String^>^ result = gcnew array<String^>(count);
        for (int i = 0; i < count; i++)
        {
            result[i] = /* i-th string from the DLL */ ;
        }

        return result;
    }

    ...
}

您可能会发现关于 C++/CLI 数组的 this article on CodeProject 也是一个有趣的阅读材料。


P.S. 从您的本机 DLL 返回的字符串采用 char-strings 的形式。另一方面,.NET 字符串是 Unicode UTF-16 字符串。因此,您需要明确使用什么编码来表示本机字符串中的文本,并将 .NET 字符串转换为 UTF-16。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2010-12-03
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多