简体   繁体   English

如何从C#/ WPF项目中调用C ++ DLL

[英]How do I call a C++ DLL from C#/WPF project

I have the below code: 我有以下代码:

namespace WPFMuskTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [DllImport
            ("myDll.DLL", 
             EntryPoint = "?Func1@FUllNameCopiedFromDependancyWalker",
             CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl
            )
        ]
        public static extern System.IntPtr Func1(out System.IntPtr handle, int type, out  DateTime date);

        public MainWindow()
        {
            InitializeComponent();
            //
            // 
            // 
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            System.IntPtr MainParam;
            int thetype = 1
            DateTime date;

            System.IntPtr res = GetFxIRMoveForDate(out MainParam, thetype _til, out date);
        }
    }
}

The exe is in the same path as the called DLL and the function definitely exists in the DLL (verified in DependacyWalker) but I keep getting the error: 该exe与所调用的DLL位于同一路径中,并且该函数肯定存在于DLL中(在DependacyWalker中进行了验证),但我不断收到错误消息:

The function prototype being called is: 调用的函数原型为:

class __declspec(dllexport) OUR_DATE_TYPE { .... } 类__declspec(dllexport)OUR_DATE_TYPE {....}

typedef unsigned long TYPE; typedef unsigned long TYPE; typedef DATE_TYPE OUR_DATE_TYPE; typedef DATE_TYPE OUR_DATE_TYPE;

namespace1
{
namespace2
{
void func1(MyClass &myclass, const TYPE& type, const DATE_TYPE& date);
}
}

An unhandled exception of type 'System.AccessViolationException' 类型为“ System.AccessViolationException”的未处理异常

Can anyone tell me why? 谁能告诉我为什么?

By default, c++ does not use the cdecl calling convention, it uses stdcall . 默认情况下,c ++不使用cdecl调用约定,而是使用stdcall You would probably have more success writing ac wrapper to the c++ api and calling that instead, because C has a well-defined ABI . 您可能会更成功地将ac包装器写入c ++ api并调用它,因为C具有定义明确的ABI

EDIT: looking at your code again, I doubt DateTime is the same as the date type you're using in C++. 编辑:再次查看您的代码,我怀疑DateTime是否与您在C ++中使用的日期类型相同。 If it's the wrong size, for example, this error could occur. 例如,如果尺寸错误,则可能会发生此错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM