Windows c export function

EXPORTS

Introduces a section of one or more export definitions that specify the exported names or ordinals of functions or data. Each definition must be on a separate line.

Remarks

The first definition can be on the same line as the EXPORTS keyword or on a subsequent line. The .DEF file can contain one or more EXPORTS statements.

The syntax for an export definition is:

entryname[=internal_name|other_module.exported_name] [@ordinal [NONAME] ] [ [PRIVATE] | [DATA] ]

entryname is the function or variable name that you want to export. This is required. If the name that you export differs from the name in the DLL, specify the export’s name in the DLL by using internal_name. For example, if your DLL exports a function func1 and you want callers to use it as func2 , you would specify:

If the name that you export is from some other module, specify the export’s name in the DLL by using other_module.exported_name. For example, if your DLL exports a function other_module.func1 and you want callers to use it as func2 , you would specify:

If the name that you export is from another module that exports by ordinal, specify the export’s ordinal in the DLL by using other_module.#ordinal. For example, if your DLL exports a function from the other module where it is ordinal 42, and you want callers to use it as func2 , you would specify:

Because the MSVC compiler uses name decoration for C++ functions, you must either use the decorated name internal_name or define the exported functions by using extern «C» in the source code. The compiler also decorates C functions that use the __stdcall calling convention with an underscore (_) prefix and a suffix composed of the at sign (@) followed by the number of bytes (in decimal) in the argument list.

To find the decorated names produced by the compiler, use the DUMPBIN tool or the linker /MAP option. The decorated names are compiler-specific. If you export the decorated names in the .DEF file, executables that link to the DLL must also be built by using the same version of the compiler. This ensures that the decorated names in the caller match the exported names in the .DEF file.

You can use @ordinal to specify that a number, and not the function name, goes into the DLL’s export table. Many Windows DLLs export ordinals to support legacy code. It was common to use ordinals in 16-bit Windows code, because it can help minimize the size of a DLL. We don’t recommend exporting functions by ordinal unless your DLL’s clients need it for legacy support. Because the .LIB file will contain the mapping between the ordinal and the function, you can use the function name as you normally would in projects that use the DLL.

By using the optional NONAME keyword, you can export by ordinal only and reduce the size of the export table in the resulting DLL. However, if you want to use GetProcAddress on the DLL, you must know the ordinal because the name will not be valid.

The optional keyword PRIVATE prevents entryname from being included in the import library generated by LINK. It does not affect the export in the image also generated by LINK.

Читайте также:  Vmware airwatch windows geolocation service

The optional keyword DATA specifies that an export is data, not code. This example shows how you could export a data variable named exported_global :

There are four ways to export a definition, listed in recommended order:

The __declspec(dllexport) keyword in the source code

An EXPORTS statement in a .DEF file

An /EXPORT specification in a LINK command

A comment directive in the source code, of the form #pragma comment(linker, «/export: definition «) . The following example shows a #pragma comment directive before a function declaration, where PlainFuncName is the undecorated name, and _PlainFuncName@4 is the decorated name of the function:

The #pragma directive is useful if you need to export an undecorated function name, and have different exports depending on the build configuration (for example, in 32-bit or 64-bit builds).

All four methods can be used in the same program. When LINK builds a program that contains exports, it also creates an import library, unless an .EXP file is used in the build.

Here’s an example of an EXPORTS section:

When you export a variable from a DLL by using a .DEF file, you do not have to specify __declspec(dllexport) on the variable. However, in any file that uses the DLL, you must still use __declspec(dllimport) on the declaration of data.

/EXPORT (экспортирует функцию) /EXPORT (Exports a Function)

Экспортирует функцию по имени или порядковому номеру или данным из программы. Exports a function by name or ordinal, or data, from your program.

Синтаксис Syntax

/Export:Имязаписи[, @Ordinal[, имя]] [, Data] /EXPORT:entryname[,@ordinal[,NONAME]][,DATA]

Комментарии Remarks

Параметр /Export указывает функцию или элемент данных для экспорта из программы, чтобы другие программы могли вызывать функцию или использовать данные. The /EXPORT option specifies a function or data item to export from your program so that other programs can call the function or use the data. Экспорты обычно определяются в библиотеке DLL. Exports are usually defined in a DLL.

Имязаписи — это имя функции или элемента данных, которое будет использоваться вызывающей программой. The entryname is the name of the function or data item as it is to be used by the calling program. Ordinal указывает индекс в таблице EXPORTS в диапазоне от 1 до 65 535; Если порядковый номер не указан, ссылка назначает одну. ordinal specifies an index into the exports table in the range 1 through 65,535; if you do not specify ordinal, LINK assigns one. Ключевое слово « имя » экспортирует функцию только в качестве порядкового номера без типа Имязаписи. The NONAME keyword exports the function only as an ordinal, without an entryname.

Ключевое слово Data указывает, что экспортируемый элемент является элементом данных. The DATA keyword specifies that the exported item is a data item. Элемент данных в клиентской программе должен быть объявлен с помощью модификатора extern __declspec (dllimport). The data item in the client program must be declared using extern __declspec(dllimport).

Существует четыре метода для экспорта определения, перечисленные в рекомендуемом порядке использования: There are four methods for exporting a definition, listed in recommended order of use:

Инструкция EXPORTS в DEF-файле An EXPORTS statement in a .def file

спецификация /EXPORT в команде LINK; An /EXPORT specification in a LINK command

Директива комментария в исходном коде формы #pragma comment(linker, «/export: definition «) . A comment directive in the source code, of the form #pragma comment(linker, «/export: definition «) .

Все эти методы можно использовать в одной программе. All these methods can be used in the same program. Когда LINK создает программу, содержащую exports, она также создает библиотеку импорта, если EXP-файл не используется в сборке. When LINK builds a program that contains exports, it also creates an import library, unless an .exp file is used in the build.

Читайте также:  Консольный компилятор c для windows

LINK использует декорированные формы идентификаторов. LINK uses decorated forms of identifiers. Компилятор добавляет идентификатор при создании OBJ-файла. The compiler decorates an identifier when it creates the .obj file. Если параметр Имязаписи указан для компоновщика в недекорированной форме (как он отображается в исходном коде), LINK пытается сопоставить имя. If entryname is specified to the linker in its undecorated form (as it appears in the source code), LINK attempts to match the name. Если не удается найти уникальное совпадение, LINK выдает сообщение об ошибке. If it cannot find a unique match, LINK issues an error message. Используйте средство dumpbin для получения декорированного имени идентификатора, если необходимо указать его для компоновщика. Use the DUMPBIN tool to get the decorated name form of an identifier when you need to specify it to the linker.

Не указывайте декорированную форму идентификаторов C, которые объявляются __cdecl или __stdcall . Do not specify the decorated form of C identifiers that are declared __cdecl or __stdcall .

Если необходимо экспортировать недекорированное имя функции и выполнить различные операции экспорта в зависимости от конфигурации сборки (например, в 32-разрядных или 64-разрядных сборках), можно использовать разные DEF-файлы для каждой конфигурации. If you need to export an undecorated function name, and have different exports depending on the build configuration (for example, in 32-bit or 64-bit builds), you can use different DEF files for each configuration. (В DEF-файлах не допускаются условные директивы препроцессора.) В качестве альтернативы можно использовать #pragma comment директиву перед объявлением функции, как показано здесь, где PlainFuncName — это недекорированное имя, а _PlainFuncName@4 — декорированное имя функции: (Preprocessor conditional directives are not allowed in DEF files.) As an alternative, you can use a #pragma comment directive before a function declaration as shown here, where PlainFuncName is the undecorated name, and _PlainFuncName@4 is the decorated name of the function:

Задание данного параметра компоновщика в среде разработки Visual Studio To set this linker option in the Visual Studio development environment

Откройте диалоговое окно Страницы свойств проекта. Open the project’s Property Pages dialog box. Подробнее см. в статье Настройка компилятора C++ и свойства сборки в Visual Studio. For details, see Set C++ compiler and build properties in Visual Studio.

Перейдите на страницу свойств Свойства конфигурации > Компоновщик > Командная строка. Select the Configuration Properties > Linker > Command Line property page.

Введите параметр в поле Дополнительные параметры . Enter the option into the Additional Options box.

Экспорт функций на языке C для использования в исполняемых файлах, исходный код которых написан на языке C или C++ Exporting C Functions for Use in C or C++ Language Executables

Если в библиотеке DLL, написанной на языке C, есть функции, к которым требуется получать доступ из модуля на языке C или C++, следует использовать макрос препроцессора __cplusplus для определения компилируемого языка, а затем объявить эти функции с компоновкой C, если они используются из модуля на языке C++. If you have functions in a DLL written in C that you want to access from a C language or C++ language module, you should use the __cplusplus preprocessor macro to determine which language is being compiled, and then declare these functions with C linkage if being used from a C++ language module. При использовании такого приема и предоставлении файлов заголовков для библиотеки DLL функции можно использовать как в C, так и в C++ без изменений. If you use this technique and provide header files for your DLL, these functions can be used by C and C++ users with no change.

В следующем коде показан файл заголовка, который может использоваться в клиентских приложениях как на C, так и на C++: The following code shows a header file that can be used by C and C++ client applications:

Читайте также:  Lxml install mac os

Если необходимо связать функции C с исполняемым файлом C++, но для файлов заголовков в объявлении функции не использовался описанный выше метод, в исходном файле C++ следует выполнить следующие действия, чтобы компилятор не декорировал имена функций на C: If you need to link C functions to your C++ executable and the function declaration header files have not used the above technique, in the C++ source file, do the following to prevent the compiler from decorating the C function names:

Exporting functions from a DLL with dllexport

I’d like a simple example of exporting a function from a C++ Windows DLL.

I’d like to see the header, the .cpp file, and the .def file (if absolutely required).

I’d like the exported name to be undecorated. I’d like to use the most standard calling convention ( __stdcall ?). I’d like the use __declspec(dllexport) and not have to use a .def file.

I’m trying to avoid the linker added underscores and/or numbers (byte counts?) to the name.

I’m OK with not supporting dllimport and dllexport using the same header. I don’t want any information about exporting C++ class methods, just c-style global functions.

UPDATE

Not including the calling convention (and using extern «C» ) gives me the export names as I like, but what does that mean? Is whatever default calling convention I’m getting what pinvoke (.NET), declare (vb6), and GetProcAddress would expect? (I guess for GetProcAddress it would depend on the function pointer the caller created).

I want this DLL to be used without a header file, so I don’t really need the a lot of the fancy #defines to make the header usable by a caller.

I’m OK with an answer being that I have to use a *.def file.

4 Answers 4

If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc. ). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option «Compile As» which corresponds to the compiler switches /TP and /TC.

If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.

Exporting/Importing DLL Libs in VC++

What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:

Then on a function that you want to be exported you use LIBRARY_API :

In your library build project create a define LIBRARY_EXPORTS this will cause your functions to be exported for your DLL build.

Since LIBRARY_EXPORTS will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.

If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:

When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.

Exporting unmangled functions from a C++ DLL for LoadLibrary/PInvoke

If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern «C» inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don’t need to do the ifdef dance from above, just a simple dllexport:

And here’s what the exports look like with Dumpbin /exports:

Оцените статью