I'm trying to create a C++ dynamic library that won't have a class. I'd like it to work similar to how you can include <string.h> and call strlen directly.
I can create a class that will compile, but won't link correctly with my library.
Here's the test library I'm working on now:
Header
#ifndef _DLL_H_
#define _DLL_H_
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved);
extern "C" __declspec(dllexport) int testMethod(int a);
#endif
Cpp
#include "dll.h"
int testMethod(int num)
{
std::cout << "test message" << std::endl;
return 1;
}
BOOL APIENTRY DllMain (HINSTANCE hInst, // Library instance handle. ,
DWORD reason, // Reason this function is being called. ,
LPVOID reserved) // Not used. )
{
switch (reason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
// Returns TRUE on success, FALSE on failure
return TRUE;
}
Finally, here's the class I'm using to test the Dll, which is told to link against the lib mingw outputs
#include <iostream>
#include "../Dll/dll.h"
using namespace std;
int main(int argc, char *argv[])
{
testMethod(5);
}
I haven't used C++ in about a year so I'm pretty rusty
extern "C" __declspec(dllexport) int testMethod(int a);
This needs to be dllimport in the application which is linking against the DLL. Most people compile their DLL with a #define which controls if it is an export or an import.
#ifdef INSIDE_MYDLL
#define MYDLLAPI __declspec(dllexport)
#else
#define MYDLLAPI __declspec(dllimport)
#endif
extern "C" MYDLLAPI int testMethod(int a);
Related
Hi I'm sorry I've seen that there is a lot of "unresolved external symbol error" questions, and I've seen them but none of the answers that I found fixed my error.
I've tested 2 ways to compile the DLL and use the HelloWorld method from SerialPort class.
btw I'm using VS2019 community edition
Both ways are throwing the same error :
Error LNK2019 unresolved external symbol "public: void __thiscall SerialPort::HelloWorld(void)" (?HelloWorld#SerialPort##QAEXXZ) referenced in function _main Test DriverCore C:\Users\$USER\source\repos\Test DriverCore\Test DriverCore\Main.obj 1
To what I've understood it's a linker error and the name of the method that I'm using is unresolved (not found) but I have no idea how to fix that (I thought that extern "C" prevented this to happen)
I've also tried to add #pragma comment(lib, "DriverCore.lib")(with DriverCore.lib in the same Dir as DriverCore.h) but still nothing :/
Way 1
using a function to return a pointer to the class
DriverCore.h
#pragma once
#ifdef DRIVERCORE_EXPORTS
#define DLLCALL __declspec(dllexport)
#else
#define DLLCALL __declspec(dllimport)
#endif
class SerialPort
{
private:
bool connected = 0;
public:
SerialPort() {};
void HelloWorld();
bool isConnected() { return 0; };
int readSerialPort(char* buffer, unsigned int buf_size) { return 0; };
bool writeSerialPort(char* buffer, unsigned int buf_size) { return 0; };
};
extern "C" {
DLLCALL SerialPort* __stdcall CreateSerialPort();
};
DriverCore.cpp
#include "pch.h"
#include "DriverCore.h"
#include <iostream>
#define DRIVERCORE_EXPORTS
BOOL APIENTRY DllMain( HMODULE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
return TRUE;
}
SerialPort* __stdcall CreateSerialPort()
{
return new SerialPort();
}
void SerialPort::HelloWorld()
{
std::cout << "Hello World !";
}
Main.cpp
#include "pch.h"
#include <Windows.h>
#include <iostream>
#include "DriverCore.h"
typedef SerialPort* (__stdcall *SerialPortImported) ();
int main()
{
// instantiate the dll location
HINSTANCE hDLL = LoadLibraryW(L"DriverCore.dll");
if (!hDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
//Resolve Objects Addr
SerialPortImported pCSerialPort = (SerialPortImported) GetProcAddress(hDLL, "CreateSerialPort") ;
SerialPort* CSerialPort = pCSerialPort();
CSerialPort->HelloWorld();
return 0;
}
Way 2
without using extern "c" {...} but using __declspec directly onto the class declaration
DriverCore.h
#pragma once
#ifdef DRIVERCORE_EXPORTS
#define DLLCALL __declspec(dllexport)
#else
#define DLLCALL __declspec(dllimport)
#endif
class DLLCALL SerialPort
{
private:
bool connected = 0;
public:
SerialPort() {};
void HelloWorld();
bool isConnected() { return 0; };
int readSerialPort(char* buffer, unsigned int buf_size) { return 0; };
bool writeSerialPort(char* buffer, unsigned int buf_size) { return 0; };
};
DriverCore.cpp
#include "pch.h"
#include "DriverCore.h"
#include <iostream>
#define DRIVERCORE_EXPORTS
BOOL APIENTRY DllMain( HMODULE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
return TRUE;
}
void SerialPort::HelloWorld()
{
std::cout << "Hello World !";
}
Main.cpp
#include "pch.h"
#include <Windows.h>
#include <iostream>
#include "DriverCore.h"
int main()
{
// instantiate the dll location
HINSTANCE hDLL = LoadLibraryW(L"DriverCore.dll");
if (!hDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
//Resolve Objects Addr
SerialPort* pSerialPort = (SerialPort*) GetProcAddress(hDLL, "SerialPort") ;
pSerialPort->HelloWorld();
return 0;
}
Thanks a lot in advance for your help !
You are calling HelloWorld which is missing its implementation in your application.
There is some fundamental misunderstanding about how C++ executables are compiled and linked against DLLs.
No libraries:
All symbols that the Application needs must be defined in the Application.
All needed symbol definitions must be available to the linker.
Static libraries:
All symbols that the Application needs must be defined in the Application or a static library.
All needed symbol definitions must be available to the linker.
The symbols are added to the generated Application's executable.
Dynamic libraries:
All symbols that the Application needs must be defined in the Application or a dynamiclibrary.
All needed symbol definitions must be available to the linker.
The symbols remain at their original places and they are loaded only at load time. This allows swap the dynamic libraries with any other ABI-compatible one at load time.
Since you are not linking with the dll and only load it at runtime, the linker correctly complains about the missing HelloWorld method.
Extern "C" is irrelevant here.
I am dealing with a dll project for my internship. I have to write a C++ code including some basic functions for pl/sql with dev c compiler and it must be work as a pl/sql tool.I wrote this codes.And i save the source file as dll file.I copied the dll extension file to plugin directory of pl/sql developer.It did not work.
Thank you all.
Here is my header and source code.
// header file plsqlHx.h
#ifndef _DLL_H_
#define _DLL_H_
#define DLL_EX
#include <string>
using namespace std;
extern "C" __declspec (dllexport) DLL_EX const char* IdentifyPlugIn(int);
extern "C" __declspec (dllexport) DLL_EX const char* CreateMenuItem(int);
extern "C" __declspec(dllexport) DLL_EX void OnMenuClick(int);
#endif
#include "plsqlHx.h"
#include <iostream>
#include <windows.h>
#include <string>
const char *const Desc = "C++Builder Plug-In demo 1";
int PlugInID;
const char* IdentifyPlugIn(int ID){
PlugInID = ID;
return Desc;
}
const char* CreateMenuItem(int Index){
switch (Index)
{
case 1 : return "Tools / &Plug-In 1 Demo...";
}
return "";
}
void OnMenuClick (int Index){
switch(Index){
case 11:
cout << "Hello";
break;
case 12:
cout << "Goodbye";
break;
}
}
I have a .lib which has a function that I want to make into a DLL.
In the project properties, I have done 2 things,
1. In the C/C++ -> General -> Additional Directories: added the path for the .h file.
2. In the Linker-> General -> Additional Dependies: added the path for the .lib file
Then I made an .h file
#ifndef _DFUWRAPPER_H_
#define _DFUWRAPPER_H_
#include <windows.h>
#include "DFUEngine.h"
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) void helloworld(void);
__declspec(dllexport) void InitDLL();
#ifdef __cplusplus
}
#endif
#endif
and made the .cpp file
#include "stdafx.h"
#include "stdio.h"
#include "DFUWrapper.h"
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
void helloworld(void)
{
printf("hello world DFU");
}
DFUEngine* PyDFUEngine()
{
return new DFUEngine();
}
void delDFUEngine(DFUEngine *DFUe)
{
DFUe->~DFUEngine();
}
void PyInitDLL(DFUEngine *DFUe)
{
return DFUe->InitDLL();
}
I made a test with the function helloword. I can see this function in the DLL but not the InitDLL function.
How can I come around this? Please help
Define the following in your DLL header file
#if defined (_MSC_VER)
#if defined (MY_DLL_EXPORTS)
#define MY_EXPORT __declspec(dllexport)
#else
#define MY_EXPORT __declspec(dllimport)
#endif
#else
#define MY_EXPORT
#endif
Declare your function using that macro
#ifdef __cplusplus
extern "C" {
#endif
MY_EXPORT void helloworld(void);
MY_EXPORT void InitDLL();
#ifdef __cplusplus
}
#endif
And in your .cpp
MY_EXPORT void helloworld(void)
{
printf("hello world DFU");
}
MY_EXPORT void InitDLL()
{
/// blahblah
}
Compile your DLL with MY_DLL_EXPORT defintion....
But be sure that it's not define when you want IMPORT ....
I like exporting functions from DLLs using .DEF files.
This has the added benefit of avoiding name mangling: not only the C++ complex mangling, but also the one happening with __stdcall and extern "C" functions (e.g. _myfunc#12).
You may want to simply add a DEF file for your DLL, e.g.:
LIBRARY MYDLL
EXPORTS
InitDLL #1
helloworld #2
... other functions ...
I have the following code:
//mydll.cpp
#include <Windows.h>
#include <io.h>
#define STDOUT_FILEDESC 1
class MYSTDOUT {
bool shouldClose;
bool isBuffered;
public:
MYSTDOUT(bool buf = true, bool cl = true)
: isBuffered(buf),
shouldClose(cl)
{}
~MYSTDOUT() {
if (shouldClose) {
close(STDOUT_FILEDESC);
}
}
};
__declspec(dllexport) void* mydll_init_stdout()
{
static MYSTDOUT outs;
return &outs;
}
//test_dll.cpp
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <io.h>
typedef void* (__cdecl *MYPROC)(void);
int main(void)
{
int fd;
void *pstdout;
MYPROC init_stdout;
HMODULE handle = LoadLibrary(TEXT("mydll.dll"));
init_stdout = (MYPROC)GetProcAddress(handle,"mydll_init_stdout");//NULL
FreeLibrary((HMODULE) handle);
return 0;
}
I get that init_stdout is NULL.What could be a problem?
handle is OK(Not NULL)
Thank you
That is due to name-mangling.
You need to wrap the exported function in extern "C" as:
extern "C"
{
__declspec(dllexport) void* mydll_init_stdout()
{
static MYSTDOUT outs;
return &outs;
}
}
Have a check in Dependency Walker, or dumpbin /exports and you will see that mydll_init_stdout has been exported with a mangled C++ name. That's why the GetProcAddress call fails.
Use extern "C" to stop mangling.
extern "C"
{
__declspec(dllexport) void* mydll_init_stdout()
{
static MYSTDOUT outs;
return &outs;
}
}
I'm working on oop c++ with code::Blocks.
These are my first steps in oop because I program in C for microprocessors.
I'm having trouble linking a dll.
My the main from the dll project is:
#include "main.h"
#include "xclass.h"
// a sample exported function
void DLL_EXPORT SomeFunction(const LPCSTR sometext)
{
MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATION);
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// attach to process
// return FALSE to fail DLL load
break;
case DLL_PROCESS_DETACH:
// detach from process
break;
case DLL_THREAD_ATTACH:
// attach to thread
break;
case DLL_THREAD_DETACH:
// detach from thread
break;
}
return TRUE; // succesful
}
This is the header:
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
#include "xclass.h"
/* To use this exported function of dll, include this header
* in your project.
*/
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
void DLL_EXPORT SomeFunction(const LPCSTR sometext);
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
Basic stuff as you can see.
The problem is that I am including the class xclass with th main:
#include "xclass.h"
xclass::xclass()
{
//ctor
}
xclass::~xclass()
{
//dtor
}
and header
#ifndef XCLASS_H
#define XCLASS_H
class xclass
{
public:
xclass();
virtual ~xclass();
unsigned int GetCounter() { return m_Counter; }
void SetCounter(unsigned int val) { m_Counter = val; }
protected:
private:
unsigned int m_Counter;
};
#endif // XCLASS_H
I was able to link and use the dll in other project. A can even use the function in the DLL SomeFunction("teste x"); but I can not access and us the class:
#include <iostream>
#include "main.h"
//#include "../cvWrapper/main.h"
using namespace std;
int main()
{
xclass ClassInDll;// not working
SomeFunction("teste x"); //using the function in dll
printf("%d\n", 1);
return 0;
}
The build error is:
||=== testDLL, Debug ===| obj\Debug\main.o||In function main':|
C:\Users\SoftVision\Desktop\PrinterCode\DLL_test\testDLL\main.cpp|9|undefined
reference toxclass::xclass()'|
C:\Users\SoftVision\Desktop\PrinterCode\DLL_test\testDLL\main.cpp|14|undefined
reference to xclass::~xclass()'|
C:\Users\SoftVision\Desktop\PrinterCode\DLL_test\testDLL\main.cpp|14|undefined
reference toxclass::~xclass()'| ||=== Build finished: 3 errors, 0
warnings ===|
Thank for the help...
Actually you should export the class:
class DLL_EXPORT xclass
{
public:
xclass();
virtual ~xclass();
unsigned int GetCounter() { return m_Counter; }
void SetCounter(unsigned int val) { m_Counter = val; }
protected:
private:
unsigned int m_Counter;
};
Be careful when you export a class which is not a pure virtual class because you may meet some problems with a memory alignment. This happens because of different RTL versions in a different compilers. Instead export a pure virtual interface of you class.
class DLL_EXPORT IXClass
{
public:
IXClass();
virtual ~IXClass();
virtual unsigned int GetCounter()=0;
virtual void SetCounter(unsigned int val) =0;
};
Also avoid macros...
Good luck :).
You need to export the class too:
class DLL_EXPORT xclass {
//...
You might need to rearrange your headers a little - e.g. put the #define for DLL_EXPORT somewhere that can be included in both 'main.h' and 'xclass.h'.
http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL