【发布时间】:2016-07-24 23:35:27
【问题描述】:
我已经研究了几天,并且阅读了很多问题,这些问题帮助我到达了现在的位置。但我仍然需要一些帮助。
我会解释的。我有一个 C++ DLL,我想包装它以便在 c# 中使用它。我有 DLL 的文档,但我无法更改它的任何内容。很多功能都适用于基本的 dllimport 设置,但我有一些功能无法正常工作,这是其中之一:
DLL documentation
struct stChannel LookForAvailableChannels (const char *dataBaseFolder, int serialNumber, double firstLogTime, double lastLogTime)
我也有这些结构:
struct stChannelInfo
{
char ChannelTag[17];
char ChannelEnabled;
}
struct stChannel
{
int ChannelNumber;
struct stChannelInfo *ChannelInfo;
}
所以尝试不同的东西,在阅读了很多之后,我得出了一个“部分”有效的解决方案:
C# Code
[StructLayout(LayoutKind.Sequential)]
public struct stChannelInfo
{
public IntPtr ChannelTag;
public byte ChannelEnabled;
};
[StructLayout(LayoutKind.Sequential)]
public struct stChannel {
public int ChannelNumber;
public stChannelInfo ChannelInfo;
};
[DllImport("NG.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
public static extern stChannel LookForAvailableChannels(string dataBaseFolder, int serialNumber, double firstLogTime, double lastLogTime);
stChannel Estructura = new stChannel();
我有一个调用按钮会触发这段代码:
Estructura = LookForAvailableChannels("C:\\Folder", 12345678, FechaInicio, FechaFinal);
然后我编组 Estructura.ChannelInfo.ChannelTag:
string btListFile = Marshal.PtrToStringAnsi(Estructura.ChannelInfo.ChannelTag);
这确实有效,它返回的数据我知道它是正确的。但是我只接收数组的第一个元素,因为 stChannel 内部的 stChannelInfo 结构是一个指针,我不知道如何在 c# 中处理它。
应该以我现在使用的这段代码的方式完成:
Marshal.PtrToStringAnsi(Estructura.ChannelInfo.ChannelTag);
应该是
Marshal.PtrToStringAnsi(Estructura.ChannelInfo[i].ChannelTag);
但是我现在使用的所有东西都不起作用。我将不胜感激。
谢谢。
编辑:
感谢用户 Adriano Repetti,现在我有了这个:
C# 代码 [StructLayout(LayoutKind.Sequential)] 公共结构 stChannelInfo { [MarshalAs(UnmanagedType.LPStr, SizeConst = 17)] 公共字符串 ChannelTag; 公共字节 ChannelEnabled; };
[StructLayout(LayoutKind.Sequential)]
public struct stChannel {
public int ChannelNumber;
public IntPtr ChannelInfo;
};
[DllImport("NG.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern stChannel LookForAvailableChannels(string dataBaseFolder, int serialNumber, double firstLogTime, double lastLogTime);
stChannel Estructura = new stChannel();
我有一个调用按钮会触发这段代码:
Estructura = LookForAvailableChannels("C:\\Folder", 12345678, FechaInicio, FechaFinal);
var channelinf = (stChannelInfo)Marshal.PtrToStructure(Estructura.ChannelInfo, typeof(stChannelInfo));
for (int i = 0; i < 4; i++)
{
var ptr = IntPtr.Add(Estructura.ChannelInfo, Marshal.SizeOf(typeof(stChannelInfo)) * i);
var channelll = (stChannelInfo)Marshal.PtrToStructure(ptr, typeof(stChannelInfo));
}
现在的问题是我在这里得到了一个 AccessViolationException:
Estructura = LookForAvailableChannels("C:\\Folder", 12345678, FechaInicio, FechaFinal);
但我真的不知道为什么,我会很感激任何帮助。
【问题讨论】: