Last active
June 26, 2020 18:10
-
-
Save jlschrag/45aa468cb43272c825d6d7ca14f4622b to your computer and use it in GitHub Desktop.
Passing an interface from a Linux shared library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cmake_minimum_required (VERSION 3.13) | |
project (ConsumingProject) | |
add_executable (ConsumingProject "ConsumingProject.cpp" "ConsumingProject.h") | |
if (UNIX) | |
target_link_libraries(ConsumingProject "${CMAKE_DL_LIBS}") #Allows us to include dlfcn.h to link shared (dynamic) libraries | |
endif() | |
find_library(SHARED_LIB_LOCATION SharedLib PATHS ${CMAKE_BINARY_DIR}) #Assumes library's .so files have been copied into the same directory as this file | |
target_link_libraries(ConsumingProject "${SHARED_LIB_LOCATION}") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ConsumingProject.h" | |
#include "InterfaceTypes.h" | |
#include <dlfcn.h> | |
#include <iostream> | |
int main() | |
{ | |
void* handle = dlopen("libSharedLib.so", RTLD_NOW); | |
if (!handle) | |
{ | |
std::cout << dlerror() << std::endl; | |
} | |
MyInterface theInterface; | |
theInterface.GetCustomReturnType = (MyCustomReturnType(*)(MyCustomParameterType))dlsym(handle, "GetCustomReturnType"); | |
MyCustomParameterType param = 1; | |
MyCustomReturnType returnStruct = theInterface.GetCustomReturnType(param); | |
char* error = dlerror(); | |
if (nullptr != error) | |
{ | |
std::cout << error << std::endl; | |
} | |
else | |
{ | |
std::cout << "Return value: " << returnStruct.Result << std::endl; | |
} | |
dlclose(handle); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
extern "C" | |
{ | |
typedef long MyCustomParameterType; | |
typedef struct MyCustomReturnType | |
{ | |
long Result; | |
} MyCustomReturnType; | |
typedef struct MyInterface | |
{ | |
MyCustomReturnType (*GetCustomReturnType)(MyCustomParameterType); | |
} MyInterface; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment