导入C ++ DLL在C#项目 [英] Importing c++ dll in c# project
问题描述
我进口一些C ++ DLL到C#项目中,我使用Visual Studio 2010中我已经succeded导入使用功能内置型,但是我得到的错误,当我试图处理结构。这是一个简单的例子:
I am importing some c++ dll into a c# project, I am using visual studio 2010. I have succeded to import function that are using built-in type, however I am getting error when I have tried to deal with structure. This is a simple example:
C ++代码
typedef long int TDate;
typedef struct _TMDYDate
{
long month; /* In range [1,12] */
long day; /* In range [1-31] */
long year; /* In range [1600-] */
} TMonthDayYear;
int JpmcdsDateToMDY
(TDate date, /* (I) TDate format */
TMonthDayYear *mdyDate);
和我已经翻译到C#为:
and I have translated to c# as:
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct TMonthDayYear {
public int month;
public int day;
public int year;
}
public partial class NativeMethods {
[System.Runtime.InteropServices.DllImportAttribute("MyDll.dll", EntryPoint="JpmcdsDateToMDY")]
public static extern int JpmcdsDateToMDY(int date, ref TMonthDayYear mdyDate) ;
}
当我尝试在我的测试程序运行的功能我得到这个错误:
when I try to run the function in my test program I get this error:
未处理的异常:System.AccessViolationException:尝试读取或写入受保护的内存。这通常是指示其他内存已损坏。在CsharpWrapper.NativeMethods.JpmcdsDateToMDY(的Int32日期,TMonthDayYear&安培; MDY日)
该结构的声明在堆栈中,我认为(也许)是问题但我仍然得到,即使我有改变TMonthDayYear上课同样的错误。
The struct are declare in the stack and I thought (maybe) was the problem but I am still getting the same error even though I have change TMonthDayYear to class.
我在做什么错了?
感谢您的帮助。
推荐答案
您必须使用CallingConvention属性的函数[DllImport]属性,这是CDECL因为你没有在本地函数声明中使用__stdcall。虽然这是错误的,它不是为AV一个很好的解释。您需要调试C代码,该AV表明,它有一个指针错误。项目+属性,调试,勾选启用非托管代码调试,并设置在C函数中设置断点。
You have to use the CallingConvention property in the [DllImport] attribute, this is Cdecl since you didn't use __stdcall in the native function declaration. While that's wrong, it is not a great explanation for the AV. You need to debug the C code, the AV suggests it has a pointer bug. Project + Properties, Debug, tick "Enable unmanaged code debugging" and set a breakpoint on the C function.
坦率地说,一个日期转换这样应该写在纯C#
Frankly, a date conversion like this should be written in pure C#.
这篇关于导入C ++ DLL在C#项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!