如何用C编写DLL文件? [英] How to write a DLL file in C?

查看:101
本文介绍了如何用C编写DLL文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 DLL 文件/en.wikipedia.org/wiki/C_%28programming_language%29" rel="noreferrer">C?

How do I write a DLL file in C?

我在网上看,但我总是得到C++,不是 C.我想用 C 编写我的第一个 DLL 文件.我该怎么做?一个简短的例子是什么?

I was looking online, but I always get tutorials for C++, not C. I want to write my first DLL file in C. How can I do that? What would a short example be?

推荐答案

让我们开始您的第一个 DLL:

Let's get you started on your first DLL:

  • 启动 Visual Studio .NET.
  • 转到菜单文件 -> 新建 -> 项目.
  • 选择 Visual C++ 项目,然后从 Templates 中选择 Win32 Project.
  • 为您的项目命名.这将是最终 DLL 文件的名称.
  • 按确定.
  • Application Type 中选择 DLL(在 Application Settings 选项卡中).
  • 勾选Empty Project,然后按Finish.
  • Start Visual Studio .NET.
  • Go to menu File -> New -> Project.
  • Select Visual C++ Project, and from the Templates, select Win32 Project.
  • Give the name to your project. This will be the name of your final DLL file.
  • Press OK.
  • Select DLL from Application Type (In the Application Settings tab).
  • Check Empty Project and press Finish.

您需要将一个空的源文件附加到空白项目中:

You need to attach an empty source file to the blank project:

  • 启动解决方案资源管理器(如果未显示).
  • 右键单击Source FilesAdd -> Add New Item 然后选择C++ File 和给它起个名字.
  • 打开.
  • Start Solution Explorer (if it’s not displayed).
  • Right click to the Source Files, Add -> Add New Item and then select C++ File and give the name to it.
  • Press Open.

在打开的窗口中,输入以下代码:

In the opened window, enter the following code:

#include <stdio.h>
extern "C"
{
    __declspec(dllexport) void DisplayHelloFromMyDLL()
    {
        printf ("Hello DLL.
");
    }
}

  • __declspec(dllexport) 是一个强制前缀,它使外部应用程序可以使用 DLL 函数.

    • __declspec(dllexport) is an obligatory prefix which makes DLL functions available from an external application.

      extern C"(带大括号,用于范围)表明括号内的所有代码都可以从文件外部"获得.尽管即使没有这个语句代码也能编译,但在运行时,你会得到一个错误.(我把这个留作你的实验).

      extern "C" (with braces, for scoping) shows that all code within brackets is available from "outside" the file. Although code will compile even without this statement, during runtime, you will get an error. (I leave this as an experiment for you).

      构建此应用程序,您的 DLL 文件已准备就绪.

      Build this application and your DLL file is ready.

      参考演练:创建和使用动态链接库 了解更多关于如何添加内容的信息.

      Refer to Walkthrough: Creating and Using a Dynamic Link Library for more information on how to do addition and stuff.

      这篇关于如何用C编写DLL文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆