gpt4 book ai didi

c# - 从 C# 程序的 DLL 访问方法

转载 作者:太空狗 更新时间:2023-10-29 17:23:13 25 4
gpt4 key购买 nike

我有一个 C 程序,我已经创建了一个 DLL 文件。我正在使用 Windows Vista 和 Visual C++。

现在我需要从该 DLL 访问一个方法,从 C# 代码的 Main() 方法。这样做的步骤是什么?

至此我已经添加了DLL文件作为引用,之后我应该做什么?

这只是一个例子:

int main1( void ) {
prinf("Hello World");
}

请注意,此类还使我们可以使用其他 .lib 函数,但我能够成功地从中创建一个 DLL。 (我不知道这是否相关)

现在我需要从我的 C# Main() 访问这个方法;

[STAThread]
static void Main()
{
// I need to call that main1() method here

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}

最佳答案

参见 using a class defined in a c++ dll in c# code这有一个很好的公认答案。正如 Hans Passant 在评论中所写,您不能将 native DLL 添加为对 C# 项目的引用。

当我引用我自己的 native DLL 之一时,我通常在 C# 项目和生成 native DLL 的项目之间添加依赖关系,或者我将 DLL 作为链接内容文件添加到 C# 项目中,如下所示:

  1. 右键单击项目并选择“添加”>“现有项”。
  2. 浏览并选择所需的 DLL,但先不要点击添加
  3. 点击添加按钮右侧的小箭头,然后选择添加为链接
  4. 选择现在出现在您的 C# 项目中的 DLL 并转到其属性。
  5. 确保将构建操作设置为内容

这会将 DLL 复制到 C# 项目的 bin\Debug 文件夹,并确保一旦您决定创建一个安装项目,您可以轻松引用所有 内容文件 并将它们包含在 Microsoft 安装程序包中。

现在,为了能够看到在您的 native DLL 中编写的函数,您必须注意导出它们(参见 Exporting C Functions for Use in C or C++ Language ExecutablesExporting from a DLL Using __declspec(dllexport))。所以你必须在你的函数声明周围添加一个 extern "C" block (我假设你在 .cpp 源文件中编写代码,这意味着如果您不将它们声明为 extern "C",编译器将生成 mangled 函数名称:

extern "C"
{
__declspec (dllexport) void __cdecl Foo(const char* arg1);
}

...

void Foo(const char* arg1)
{
printf ("Hello %s !", arg1);
}

__declspec (dllexport) 装饰意味着编译器/链接器必须使函数从 DLL 外部可见。 __cdecl 定义了如何将参数传递给函数(标准的“C”方式)。

在您的 C# 代码中,您必须引用 DLL 的导出方法:

class Program
{
[DllImport("mydll.dll")]
internal static extern void Foo(string arg1);

static void Main()
{
Program.Foo ("Pierre");
}
}

您应该阅读 Platform Invoke Tutorial它给出了所有血淋淋的细节。

关于c# - 从 C# 程序的 DLL 访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6392372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com