名帅一个C的char [] []数组到C# [英] Marshal a C char[][] array to C#

查看:107
本文介绍了名帅一个C的char [] []数组到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了又看,并试图一切我能想到的或者已经找到建议。我仍然没有任何运气得到我所需要的数据。

I have looked and looked and tried everything I can think of or have found suggested. I'm still not having any luck getting the data I need.

我使用的是第三方的DLL,我相信这是用C写的,我需要从这个DLL在C#中访问该功能。在大多数情况下,我有这样的工作,除了一功能。我有问题,有如下头的功能:

I'm using a third party DLL, which I believe is written in C. I need to access the functions from this DLL in C#. For the most part, I have this working, except for one function. The function I'm having problems with has the following header:

uint queryNumOfServers(USHORT *NumOfServers, char ServerNames[8][16]);

我有以下的在我的C#应用​​程序中声明

I have the following declared in my C# application

[DllImport("client.dll", CharSet=CharSet.Ansi]
public static extern uint queryNumOfServers(ref short numberofServer, StringBuilder serverNames);

我把这个如下:

StringBuilder serverNames = new StringBuilder(128);
short numServers = -1;
queryNumberOfServers(ref numServers, serverNames);

的问题是,虽然numberOfServers回来等于4,我只在servernames节点获得一个名字。我在一个小的C程序测试上面的C函数。我回去numberOfServer = 4,但我也得到4名回来。

The problem is, while numberOfServers come back equal to 4, I only get one name in serverNames. I have tested the above C function in a small C program. I get back numberOfServer = 4 but I also get 4 names back.

我曾尝试没有成功如下:

I have tried the following with no success:

[DllImport("client.dll", CharSet=charSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern uint queryNumOfServers(ref short numberOfServer,[MarshalAs(UnmanagedType.LPStr)] string serverNames);

与调用此

string serverNames = new string('\0', 128);
queryNumOfServers(ref numServers, serverNames);

有没有改变servernames节点使用此选项。

There is no change to serverNames with this option.

开发环境是Visual Studio 2008中

The development environment is Visual Studio 2008.

推荐答案

很多搜索和扯头发,这是为我工作的解决方案之后。

After much searching and hair pulling, this was the solution that worked for me.

在宣布我的C#应用​​程序的函数头为:

Declared the function header in my C# application as:

[DllImport("client.dll", CharSet = CharSet.Ansi)]
public static extern uint queryNumOfServers(ref short numberOfServers, [MarshalAs(UnmanagedType.LPArray)] byte[,] serverNames);

然后叫如下:

byte[,] serverNames = new byte[8,16];
short numServers = -1;
queryNumberOfServers(ref numServers, serverNames);

这会返回一个双指数字节数组。从这里我用Buffer.BlockCopy()和Encoding.UTF8.GetString()到我的字节数组转换成字符串数组。

This returns a double index byte array. From here I used Buffer.BlockCopy() and Encoding.UTF8.GetString() to convert my byte array into a array of strings.

这篇关于名帅一个C的char [] []数组到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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