我正在尝试在C#程序中使用C语言编写的dll。我已经定义了一个包含整数和数组的简单结构。数组的长度不一定相同。我还编写了一个简单的代码,以便更好地理解它为什么不起作用。
C#程序初始化此结构并用数据填充此数组,然后传递给dll。为了检查这是否正常,dll将此结构的数组内容复制到另一个数组(已在C#中初始化)。最后,C#程序打印两个应该相同的数组,而不是大小写。
执行没有显示错误,但似乎dll无法正确解释结构的内容。 我试图使用一些元帅指令,但我对它们并不熟悉,所以它没有帮助。以下是代码,C和C#,非常感谢您的帮助。
托马斯
#THE C# CODE
#region DeclareStruct
[StructLayout(LayoutKind.Sequential)]
public struct Test
{
public double[] theVector;
public int nElements;
}
#endregion DeclareStruct
#region DLLFunctions
[DllImport("TestLib.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "readStruct")]
public static extern void readStruct(ref Test theStruct, double[] a);
#endregion DLLFunctions
static void Main(string[] args)
{
//delcare struc
Test myStruct = new Test();
myStruct.nElements = 10;//will not be always 10
myStruct.theVector = new double[myStruct.nElements];
//fills myStruct.theVector
for (int i = 0; i < myStruct.nElements; i++) myStruct.theVector[i] = i * i;
//delcare the array a which should have the same content as myStruct.theVector
double[] a = new double[myStruct.nElements];
// Initialize unmanged memory to hold the struct.
//IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(myStruct)));
//Marshal.StructureToPtr(myStruct, pnt, false);
//executes dll
readStruct(ref myStruct, a);
//display myStruct.theVector and a
Console.WriteLine("This is theVector");
for (int i = 0; i < myStruct.nElements; i++) Console.WriteLine(myStruct.theVector[i].ToString());
Console.WriteLine("This is a");
for (int i = 0; i < myStruct.nElements; i++) Console.WriteLine(a[i].ToString());
}
#THE C CODE
typedef struct Test
{
double* theVector;
int nElements;
}
Test;
__declspec (dllexport) void readStruct(Test *myTest, double *a)
{
int i;
for (i = 0; i < myTest->nElements; i++) a[i] = myTest->theVector[i];
}