Skip to content

Instantly share code, notes, and snippets.

@jlschrag
Last active June 26, 2020 18:10
Show Gist options
  • Save jlschrag/45aa468cb43272c825d6d7ca14f4622b to your computer and use it in GitHub Desktop.
Save jlschrag/45aa468cb43272c825d6d7ca14f4622b to your computer and use it in GitHub Desktop.
Passing an interface from a Linux shared library
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}")
cmake_minimum_required(VERSION 3.13) #3.13 was what I had on my WSL install.
project(SharedLib VERSION 0)
add_library(SharedLib SHARED "")
set_target_properties(SharedLib PROPERTIES VERSION ${PROJECT_VERSION})
set_target_properties(SharedLib PROPERTIES SOVERSION 1) #API Version
target_sources(SharedLib
PUBLIC
SharedLib.h
SharedLib.cpp
InterfaceTypes.h
)
#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;
}
#pragma once
extern "C"
{
typedef long MyCustomParameterType;
typedef struct MyCustomReturnType
{
long Result;
} MyCustomReturnType;
typedef struct MyInterface
{
MyCustomReturnType (*GetCustomReturnType)(MyCustomParameterType);
} MyInterface;
}
#include "SharedLib.h"
#include <iostream>
MyCustomReturnType GetCustomReturnType(MyCustomParameterType param)
{
std::cout << "Param value: " << param << std::endl;
MyCustomReturnType returnStruct;
returnStruct.Result = 123;
return returnStruct;
}
#pragma once
#include "InterfaceTypes.h"
extern "C"
{
MyCustomReturnType GetCustomReturnType(MyCustomParameterType param);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment