LoginSignup
0
1

More than 5 years have passed since last update.

Shared Libraryでコールバックを試してみた

Last updated at Posted at 2017-05-26

いつものように備忘録
ポインタから、charまでいろいろ戻せた模様

main.cpp
#include <classtest.h>
#include <iostream>

class Hoge
{
public:
    Hoge() {};
    ~Hoge() { }
    int m = 5;
    void Test(int t){
        std::printf("Hoge::Test %d \n",t);
    }
};

int some_function(int t){
    std::printf("some_function %d \n",t);
    t = t + 1;
    return t;
}

void char_function(const char * msg){
    std::printf("char_function %s \n",msg);
}

void func_function(void * func){
    std::printf("func\n");
    Hoge* a = (Hoge*)func;
    a->Test(1);
    std::cout << a->m << std::endl;
}

int main() {
    Foo foo;
    foo.print();
    foo.print2();

    Hoge hoge;
    hoge.m = 1;
    foo.funcTest(&hoge);
}
classtest.h
#ifndef CLASSTEST_H_
#define CLASSTEST_H_

#include <functional>
#include <iostream>

extern int some_function(int t);
extern void char_function(const char * msg);
extern void func_function(void * func);

class Foo
{
public:
    Foo();
    ~Foo() { }

    void Test(int t);
    void print();
    void print2();
    void funcTest(void*);
};

class EventHandler
{
public:
    void addHandler(std::function<void(int)> callback)
    {
        std::cout << "Handler added..." << std::endl;
        callback(1);
    }
};

#endif
classtest.cpp
#include <classtest.h>
#include <iostream>
#include <functional>

int i = 1;

Foo::Foo(){
  std::cout << "constructor" << std::endl;
  i = i + 1;
}

void Foo::Test(int t){
  std::printf("test %d \n",t);
}

void Foo::print(){
    int t = some_function(10);

    std::printf("print %d \n",t);
}

void Foo::print2(){
    char_function("print2");

    EventHandler* evt;
    evt->addHandler(std::bind(&Foo::Test, this, std::placeholders::_1));
}

void Foo::funcTest(void* func){
  func_function(func);
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.1.0)
project(sample)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )

set(serial "1.0.0")
set(soserial "1")
include_directories(include)
link_directories(build)
add_library(classtest SHARED classtest.cpp)

message("work dir: " ${PROJECT_SOURCE_DIR})
set_target_properties(classtest PROPERTIES VERSION ${serial} SOVERSION ${soserial})
install(TARGETS classtest LIBRARY DESTINATION ${PROJECT_SOURCE_DIR}/lib)

add_executable(sample main.cpp )
target_link_libraries(sample pthread classtest)

出力

constructor
some_function 10 
print 11 
char_function print2 
Handler added...
test 1 
func
Hoge::Test 1 
1
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1