【发布时间】:2020-05-23 06:37:51
【问题描述】:
我只有一个 lib 文件及其头文件(静态库?)我想在 C# 中使用它。从谷歌搜索我得出的结论是我需要编写一个 C# 能够使用的包装 dll。
我已经尝试在 C++ 和 C++/CLI 中编写这个,但是当我运行我的程序时,我收到一个错误,指出
无法加载 DLL 'foo.dll':找不到指定的模块。 (HRESULT 异常:0x8007007E)
我已经使用了依赖项检查器并且我的依赖项很好,所以我假设我的 dll 设置不正确。
我只是想使用库中的函数而不是类。
这是我的cs文件的一个例子
using System;
using System.Runtime.InteropServices;
using System.Text;
public class FooWrapper
{
[DllImport("FooWrapper.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern short DoSomething(ushort var);
}
// More functions like the one above
我已经将 FooWrapper.dll 添加到我的项目中,方法是进入 VS 并执行解决方案资源管理器 > 添加 > 现有项目 > 我的 dll 所在的目录 > FooWrapper.dll
对于我的 DLL,我刚刚创建了一个新的 DLL C++ 项目,添加了一个名为 FooWrapper 的类。这导致有一个项目有
Project
|
-Refrences
|
-External Dependencies
|
-Header Files
-- FooWrapper.h
-- framework.h
-- pch.h
|
-Resource Files
|
- Source Files
--FooWrapper.cpp
--dllmain.cpp
--pch.cpp
FooWrapper.h 看起来像这样
#pragma once
#ifndef FOOWRAPPER_H
#define FOOWRAPPER_H
#include <string>
#include "Foolib.h" // header file that comes with lib file i originally had
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#ifdef FOOWRAPPER_EXPORTS
#define FOOWRAPPER_API __declspec(dllexport)
#else
#define FOOWRAPPER_API __declspec(dllimport)
#endif
FOOWRAPPER_API I16 DoSomething(const I16 var) // I16 is defined (typedef) as a short
#ifdef __cplusplus
}
#endif
#endif
我还通过在 Properties>C/C++> Additional Include Directories 下添加包含目录来链接 lib 和 header
and Linker > Additional Library Directories > *FooLib.lib 所在的目录 *
and Linker > Input > Additional Dependencies > *FooLib.lib 所在的目录 *> FooLib.lib
所以最后,当我调用 DoSomething 时,代码会停止并给出来自 HRESULT 的异常:0x8007007E 错误消息。
如果我跳过了一步,有人可以告诉我吗?还是我应该使用 C++/CLI 创建库?如果是这样,我可以再试一次。或者如果没有看到 FooLib.lib 代码的实现,这是不可能的吗?
【问题讨论】:
-
尝试将您的 C++ 项目创建为 CLR 项目。只要您遵循规则(仅在 cpp 中包含本机代码),它就应该像添加您的项目作为对您的 C# 项目的引用一样简单。从记忆中开始,所以我不能肯定地说,但这可能会帮助您入门:docs.microsoft.com/en-us/cpp/dotnet/…