【问题标题】:How do I call a C++ DLL from C#/WPF project如何从 C#/WPF 项目调用 C++ DLL
【发布时间】:2012-09-24 15:26:23
【问题描述】:

我有以下代码:

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);
        }
    }
}

exe 与调用的 DLL 位于同一路径,并且该函数肯定存在于 DLL 中(在 DependacyWalker 中验证)但我不断收到错误:

被调用的函数原型是:

类 __declspec(dllexport) OUR_DATE_TYPE { …… }

typedef 无符号长类型; typedef DATE_TYPE OUR_DATE_TYPE;

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

“System.AccessViolationException”类型的未处理异常

谁能告诉我为什么?

【问题讨论】:

  • 我们确实需要查看 C# DLL 中方法的签名,以了解您是否正确键入了 DllImport。
  • 添加了 C++ 原型 - 我猜这就是你的意思?
  • 能否提供TYPEDATE_TYPE的宏定义?
  • MyClass myclassIntPtr handle 可能不对应,因为 myclass 没有作为指针传递。
  • 抱歉,已经更正了一个错字 - 请再看看!

标签: c# c++ wpf


【解决方案1】:

默认情况下,c++ 不使用cdecl 调用约定,它使用stdcall。您可能会更成功地将 c 包装器写入 c++ api 并改为调用它,因为 C 具有明确定义的 ABI

编辑:再次查看您的代码,我怀疑 DateTime 与您在 C++ 中使用的日期类型相同。例如,如果它的大小不正确,则可能会发生此错误。

【讨论】:

  • 那么应该将调用约定更改为 CallingConvention.Stdcall 吗?我已经尝试过了,错误是一样的。如果我在 C 中创建另一个包装器库以使我在 C# 中的包装器工作,我不确定它是否会顺利运行 - 这肯定可以做到吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
相关资源
最近更新 更多