【发布时间】:2015-09-10 12:54:14
【问题描述】:
我在下面有一个 C# DLL。我想在 C++ Builder 中使用这个 C# DLL。
但我不知道 C# Struct 和 C++ Struct 编组:
using RGiesecke.DllExport;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace TestLibrary
{
[ComVisible(true)]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct MyStruct
{
public int X;
public int Y;
}
public class Class1
{
[DllExport("DoSomething", CallingConvention = CallingConvention.StdCall)]
public static int DoSomething(int x, int y, ref MyStruct myStruct)
{
myStruct.X = 50;
myStruct.Y = 75;
return x + y;
}
}
}
我想从下面的 C++ Builder 传递“myStruct”参数。
void __fastcall TForm1::FormCreate(TObject *Sender)
{
struct MyStruct
{
int X;
int Y;
};
int (__stdcall *DoSomething)(int,int,MyStruct);
HINSTANCE dllHandle = NULL;
dllHandle = LoadLibrary( edtdllPath->Text.c_str());
if(dllHandle == NULL) return;
int status = -1;
try
{
DoSomething =(int (__stdcall *)(int,int,MyStruct)) GetProcAddress(dllHandle, "DoSomething");
}
catch(Exception &Err)
{
ShowMessage(Err.Message);
}
if(DoSomething != NULL)
{
try
{
MyStruct myStruct;
status = DoSomething(5,5,myStruct);
String strStatus = status;
ShowMessage(strStatus);
ShowMessage(myStruct.X);
ShowMessage(myStruct.Y);
}
catch(EAccessViolation &err)
{
ShowMessage(err.Message);
}
}
}
当我调试代码时,myStruct.X 和 myStruct.Y 的值是错误的。
我哪里错了?
【问题讨论】:
-
字符串是个大问题。你不能用
ref StringBuilder,我觉得你也不能用StringBuilder。到目前为止,最简单的解决方案是使用UnmanagedType.BStr并使用 COMBStr。您确实需要做一些备份,并且比现在更了解基础知识。 -
感谢@DavidHeffernan 的关注。我检查了 StringBuilder 参数。它正在工作。仅 myStruct 参数无效。
-
不,字符串生成器无法工作。问问自己谁将释放内存?对于初学者。还有更多的问题。你错了。
-
感谢@DavidHeffernan 你的大师
-
我已经像这样向 X 添加了地址。结构 MyStruct { int *X;双 *Y; };我得到“myStruct.X”的值,如下所示。 ShowMessage(*myStruct.X);但是 *myStruct.X 的值是错误的。
标签: c# c++ struct pinvoke marshalling