带有C#连接问题的C++/CLI Dll

本文关键字:CLI Dll C++ 连接 问题 带有 | 更新日期: 2023-09-27 18:00:41

我在一个解决方案中有3个项目。

我有:

  • 本地C++dll
  • C#Winform
  • 和一个没有纯模式的代理C++/CLI来完成其他两个项目之间的链接(并使用C#中托管代码中的本机函数)

所以当我启动应用程序时,一切都正常。但当我按下按钮";生成器";在我的winform中,我执行C++/CLI的函数NativeMethod::Test(),它崩溃了,我得到了以下弹出消息:

类型为的未处理异常'System.BadImageFormatException'发生在System.Windows.Forms.dll 中

附加信息:无法加载文件或程序集"EngineInterface Wrapper.dll"或其依赖关系。不可能应用程序Win32有效期。(例外来自HRESULT:0x800700C1)

当我进入Conf.Properties中的项目礼仪时->链接器->高级:目标机器,它设置有值";MachineX86";对于我的C++本机和托管DLL,我的WinForm也在X86中。我厌倦了很多配置,但它不起作用。

编辑:

问题可能是标题";TradeEngine.h"在C++/CLI头中:EngineInterface wrapper.h。因为当我取消本机C++Dll的链接(并删除CLI包装中的所有代码)时,如果我构建解决方案#包括";TradeEngine.h"总是在CLI标头中,我将出现相同的错误。你有主意吗?

代码:

本机C++

TradeEngine.h

#ifdef TRADEENGINE_EXPORTS
#define SYMBOL_DECLSPEC __declspec(dllexport)
#define SYMBOL_DEF
#else
#define SYMBOL_DECLSPEC __declspec(dllimport)
#define SYMBOL_DEF      __declspec(dllimport)
#endif
EXTERN_C SYMBOL_DECLSPEC void __stdcall Test(void);

TradeEngine.cpp

SYMBOL_DECLSPEC void __stdcall Test(void)
{
}

C++/CLI

EngineInterface Wrapper.h

#pragma once
#include "TradeEngine.h"
using namespace System;
using namespace System::Runtime::InteropServices;
namespace EngineInterfaceWrapper {
    public ref class NativeMethod
    {
    public:
        static void AjoutColonneDifferenceCourtClotureOuvertureReelle(void);
        static void Test();
    };
}

引擎接口包装.cpp

#pragma region Includes
#include "stdafx.h"
#include "EngineInterfaceWrapper.h"
using namespace EngineInterfaceWrapper;
#include <msclr/marshal.h>
using namespace msclr::interop;
#pragma endregion
void NativeMethod::Test()
{
    ::Test();
}

C#窗体

程序.cs

namespace TradeInterface
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Form1.cs

generaer_Click()是当用户单击Generator时按钮启动的事件。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using EngineInterfaceWrapper;
namespace TradeInterface
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void generer_Click(object sender, EventArgs e)
        {
            NativeMethod.Test();
        }
    }
}

我该怎么解决?如果您需要更多信息,请告诉我。

带有C#连接问题的C++/CLI Dll

我找到了解决方案:

http://marc.info/?l=boost-用户&m=123425857320026

在配置属性->C/C++->预处理器->预处理器中定义添加BOOST_ALL_DYN_LINK以强制使用DLL。此外,将必要的DLL复制到可执行文件驻留。例如,将boost_thread-vc90-mt-gd-1_XX.dll复制到MyApp/bin/Debug。

一个原因可能是您试图在64位进程中加载本机32位dll。确保您在应用程序中将平台目标设置为x86,以强制您的应用程序在WoW64中运行。