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;
}
}
Related
I can use code like this:
// RendererDLL.h
#pragma once
class gfx::BaseObject;
class gfx::MeshObject;
namespace gfx {
extern "C" {
void __declspec(dllexport) InitGraphics(UINT width, UINT height, HWND hwnd);
void __declspec(dllexport) ReleaseGraphics();
}
}
I don't use a class for the return type and parameters. And this code works.
But I can't use code like this:
namespace gfx {
extern "C" {
void __declspec(dllexport) EnqueueObject(gfx::BaseObject* pBaseObj);
}
}
or
namespace gfx {
extern "C" {
__declspec(dllexport) gfx::MeshObject* CreateMeshObject();
}
}
This code uses classes for the return type or parameter type.
I get errors. First, at EnqueueObject():
linkage specification is incompatible with previous "gfx::EnqueueObject"
Second, at CreateMeshObject():
cannot overload functions distinguished by return type alone
// RendererDLL.cpp
#include "pch.h"
#include "RendererDLL.h"
#include "Graphics.h"
#include "BaseObject.h"
#include "MeshObject.h"
#include "RenderQueue.h"
void gfx::EnqueueObject(gfx::BaseObject* pBaseObj) {
gfx::RenderQueue::GetInstance().Enqueue(pBaseObj);
}
gfx::MeshObject* gfx::CreateMeshObject() {
return new gfx::MeshObject();
}
This code is in a .cpp file.
I think the first error occurs because of using a class for the return type or parameter type. But I don't know why.
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 have a dll with lib.h:
#pragma once
#ifdef EXPORTS
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
extern "C" API void test1(std::vector<ValueType*>* functions);
and lib.cpp:
#include "pch.h"
#include <iostream>
#include <vector>
#include "ValueType.h"
#include "NumberValue.h"
#include "TestLib.h"
void test1(std::vector<ValueType*>* functions) {
functions->push_back(new NumberValue(123321));
And main file, that uses this dll is:
#include <iostream>
#include <vector>
#include <Windows.h>
#include "ValueType.h"
using namespace std;
typedef void (__cdecl* importedInitFunction)(std::vector<ValueType*>*);
importedInitFunction test1F;
std::vector<ValueType*> values;
int main() {
while (1) {
HMODULE lib = LoadLibrary("DllTest1.dll");
test1F = (importedInitFunction)GetProcAddress(lib, "test1");
test1F(&values);
FreeLibrary(lib);
std::cout << values.at(0)->asString();
system("pause");
}
return 0;
}
When I'm trying to compile my code, I catch an error because values.at(0) is removed.
How to prevent deleting my variable when calling FreeLibrary(lib) ? or
How to implement alternative way ?
Another classes that used:
ValueType.h:
#pragma once
#include <string>
class ValueType {
public:
virtual double asDouble() { return 999; }
virtual std::string asString() { return ""; }
};
NumberValue.h:
#pragma once
#include <string>
#include "ValueType.h"
class NumberValue : public ValueType {
public:
double m_value;
NumberValue(double value) : m_value(value) {}
virtual double asDouble() {
return m_value;
}
virtual std::string asString() {
return std::to_string(m_value);
}
};
I get this error:
FATAL ERROR:
lua_pcall() failed: error loading module 'foo' from file 'C:\Users\Commander\Desktop\Platform\Debug\foo.dll':
The specified procedure could not be found.
I load my DLL file in Lua:
require("foo")
My DLL code, I use Visual Studio Compiler
(It compiles, no errors)
#include "stdafx.h"
#pragma comment( lib, "liblua53.a" )
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <iostream>
using namespace std;
extern "C" {
static int l_bar(lua_State *L)
{
puts("l_bar called.");
return 0;
}
void luaopen_foo(lua_State *L)
{
static const struct luaL_Reg foo[] = {
{ "bar", l_bar },
{ NULL, NULL }
};
luaL_newlib(L, foo);
lua_setglobal(L, "foo");
}
}
Is there anyway around this error, Or is it not possible to load dll files in lua
I found the example c++ code here: https://stackoverflow.com/a/12059441/8767704
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