cmake 无法在C#项目中添加对C++ DLL的引用

g6ll5ycj  于 2023-04-30  发布在  C#
关注(0)|答案(1)|浏览(165)

我用CMake创建了一个C++ DLL。C++项目由以下文件组成:

  • src/setup.cpp
  • src/setup.h
  • CMakeLists.txt

setup.cpp如下:

#include "setup.h"

int myFunction() {
    return 42;
}

setup.h如下所示:

#ifndef SETUP_DLL
#define SETUP_DLL

int myFunction();

#endif

CMakeLists.txt如下所示:

cmake_minimum_required(VERSION 3.10)

# Define the project and supported versions
project(MyLibrary VERSION 1.0.0)

# Add options for compiling the library
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

# Add the library sources
add_library(MyLibrary SHARED src/setup.h src/setup.cpp)

# Specify the directory to search for headers
target_include_directories(MyLibrary PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src)

# Specify the output name
set_target_properties(MyLibrary PROPERTIES OUTPUT_NAME "MyLibrary_${PROJECT_VERSION}")

# Specify the output path
set_target_properties(MyLibrary PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/lib")

我现在试图将这个DLL导入到C#项目中。为此,我在Visual Studio 2019中右键单击项目,选择“添加”,“引用”,“浏览”,然后选择我创建的DLL文件。但是,我收到错误消息Could not add reference to 'Path\to\file.dll'. Make sure the file is accessible and that the assembly or COM component is valid.
是什么原因导致了这个错误?如何在C#项目中成功添加对C++ DLL的引用?

ckocjqey

ckocjqey1#

Header添加了extern“C”__declspec(dllexport):

extern "C" __declspec(dllexport) int myFunction();

P/Invoke:C#调用C++ dll:

[DllImport("XX\\Temp\\Debug\\MyLibrary_1.0.0.dll")]
private static extern  int myFunction();

static void Main(string[] args)
{
   myFunction();
}

相关问题