pass member function from C++ CLI to native C callback - c++

I've got problems passing a member function of a C++ CLI class to a native C callback from a library.
To be precise its the Teamspeak 3 SDK.
You can pass a non member function using the following code without problem:
struct ClientUIFunctions funcs;
/* Initialize all callbacks with NULL */
memset(&funcs, 0, sizeof(struct ClientUIFunctions));
funcs.onConnectStatusChangeEvent = onConnectStatusChangeEvent;
But I need to pass a pointer to a member function, for example:
funcs.onConnectStatusChangeEvent = &MyClass::onConnectStatusChangeEvent;
Any other idea how to use the event within a non static member function is welcome to.
Thanks in advance!

This can only be done via a static class function because C doesn't know anything about the vtable or what object the function is part of. See below for a C++ and Managed C++ example
This could however be a work around, build a wrapper class which handles all the callbacks you need.
#include <string.h>
struct ClientUIFunctions
{
void (*onConnectStatusChangeEvent)(void);
};
class CCallback
{
public:
CCallback()
{
struct ClientUIFunctions funcs;
// register callbacks
my_instance = this;
/* Initialize all callbacks with NULL */
memset(&funcs, 0, sizeof(struct ClientUIFunctions));
funcs.onConnectStatusChangeEvent = sOnConnectStatusChangeEvent;
}
~CCallback()
{
// unregister callbacks
my_instance = NULL;
}
static void sOnConnectStatusChangeEvent(void)
{
if (my_instance)
my_instance->OnConnectStatusChangeEvent();
}
private:
static CCallback *my_instance;
void OnConnectStatusChangeEvent(void)
{
// real callback handler in the object
}
};
CCallback *CCallback::my_instance = NULL;
int main(int argc, char **argv)
{
CCallback *obj = new CCallback();
while (1)
{
// do other stuff
}
return 0;
}
Another possibility would be if the callback supports and void *args like void (*onConnectStatusChangeEvent)(void *args); which you can set from the plugin. You could set the object in this args space so in de sOnConnectStatusChangeEvent you would have something like this:
static void sOnConnectStatusChangeEvent(void *args)
{
if (args)
args->OnConnectStatusChangeEvent();
}
For managed C++ it should be something like this, however I can't get it to compile because it doesn't like the template brackets..
wrapper.h:
using namespace std;
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Text;
namespace Test
{
struct ClientUIFunctions
{
void (*onConnectStatusChangeEvent)(void);
};
public delegate void ConnectStatusChangeEvent(void);
public ref class ManagedObject
{
public:
// constructors
ManagedObject();
// destructor
~ManagedObject();
//finalizer
!ManagedObject();
event ConnectStatusChangeEvent^ OnConnectStatusChangeEvent {
void add(ConnectStatusChangeEvent^ callback) {
m_connectStatusChanged = static_cast<ConnectStatusChangeEvent^> (Delegate::Combine(m_connectStatusChanged, callback));
}
void remove(ConnectStatusChangeEvent^ callback) {
m_connectStatusChanged = static_cast<ConnectStatusChangeEvent^> (Delegate::Remove(m_connectStatusChanged, callback));
}
void raise(void) {
if (m_connectStatusChanged != nullptr) {
m_connectStatusChanged->Invoke();
}
}
}
private:
ConnectStatusChangeEvent^ m_connectStatusChanged;
};
class CCallback
{
public:
static void Initialize(ManagedObject^ obj);
static void DeInitialize(void);
private:
static void sOnConnectStatusChangeEvent(void);
static gcroot<ManagedObject^> m_objManagedObject;
};
}
wrapper.cpp:
#include <string.h>
#include "wrapper.h"
using namespace System;
using namespace Test;
void CCallback::Initialize(ManagedObject^ obj)
{
struct ClientUIFunctions funcs;
// register callbacks
m_objManagedObject = obj;
/* Initialize all callbacks with NULL */
memset(&funcs, 0, sizeof(struct ClientUIFunctions));
funcs.onConnectStatusChangeEvent = sOnConnectStatusChangeEvent;
}
void CCallback::DeInitialize(void)
{
// unregister callbacks
m_objManagedObject = nullptr;
}
void CCallback::sOnConnectStatusChangeEvent(void)
{
if (m_objManagedObject != nullptr)
m_objManagedObject->OnConnectStatusChangeEvent();
}
// constructors
ManagedObject::ManagedObject()
{
// you can't place the constructor in the header but just for the idea..
// create wrapper
CCallback::Initialize(this);
}
// destructor
ManagedObject::~ManagedObject()
{
this->!ManagedObject();
}
//finalizer
ManagedObject::!ManagedObject()
{
CCallback::DeInitialize();
}
gcroot<ManagedObject^> CCallback::m_objManagedObject = nullptr;
int main(array<System::String ^> ^args)
{
ManagedObject^ bla = gcnew ManagedObject();
while (1)
{
// do stuff
}
return 0;
}

Related

How to initialize shared pointers in constructor?

I am trying to initialize objects from other classes in my constructor as shared pointers. I need a shred pointer because I need a reference to use in another method in ...
header
class MyClass
{
public:
MyClass() ;
~MyClass() {};
void myMethod();
private:
std::shared_ptr<dds::pub::Publisher>m_pub;
std::shared_ptr<dds::domain::DomainParticipant>m_part;
};
cpp
MyClass::MyClass()
{
m_part = std::make_shared<dds::domain::DomainParticipant>(domain::default_id());
m_pub = std::make_shared<dds::pub::Publisher>(m_part);
}
MyClass::myMethod()
{
//m_part, m_pub are used here
}
what am I missing here?
Error C2039 'delegate': is not a member of 'std::shared_ptr<dds::domain::DomainParticipant>'
dds::pub::Publisher
namespace dds
{
namespace pub
{
typedef dds::pub::detail::Publisher Publisher;
}
}
Publisher
namespace dds { namespace pub { namespace detail {
typedef
dds::pub::TPublisher<org::eclipse::cyclonedds::pub::PublisherDelegate> Publisher;
} } }
PublisherDelegate
namespace dds { namespace pub { namespace detail {
typedef
dds::pub::TPublisher<org::eclipse::cyclonedds::pub::PublisherDelegate> Publisher;
} } }
class OMG_DDS_API PublisherDelegate : public
org::eclipse::cyclonedds::core::EntityDelegate
{
public:
typedef ::dds::core::smart_ptr_traits< PublisherDelegate >::ref_type ref_type;
typedef ::dds::core::smart_ptr_traits< PublisherDelegate >::weak_ref_type weak_ref_type;
PublisherDelegate(const dds::domain::DomainParticipant& dp,
const dds::pub::qos::PublisherQos& qos,
dds::pub::PublisherListener* listener,
const dds::core::status::StatusMask& event_mask);
TPublisher
template <typename DELEGATE>
class dds::pub::TPublisher : public dds::core::TEntity<DELEGATE>
{
public:
typedef dds::pub::PublisherListener Listener;
public:
OMG_DDS_REF_TYPE_PROTECTED_DC(TPublisher, dds::core::TEntity, DELEGATE)
OMG_DDS_IMPLICIT_REF_BASE(TPublisher)
TPublisher(const dds::domain::DomainParticipant& dp);
TPublisher(const dds::domain::DomainParticipant& dp,
const dds::pub::qos::PublisherQos& qos,
dds::pub::PublisherListener* listener = NULL,
const dds::core::status::StatusMask& mask = dds::core::status::StatusMask::none());
I tried the method given in answer got new error,
Error C2672 'std::dynamic_pointer_cast': no matching overloaded function in TPublisher.hpp
I guess m_pub should be initialised like this
m_pub = std::make_shared<dds::pub::Publisher>(*m_part);
The class dds::pub::Publisher a.k.a. dds::pub::TPublisher has the constructor taking const dds::domain::DomainParticipant by reference.
The answer is changed after the question has been updated.

Pass std::bind object with bind member function to a function

I want to connect a callback function to a boost signal through a public function. I can pass a function pointer just fine, but if I try to use std::bind to pass a member function, it will not compile. Giving me error saying no viable conversion. What type should I use for the App::SetCallback function argument?
#include <functional>
#include <boost/signal.hpp>
using namespace std::placeholders; // for _1, _2, _3...
//plain simple call back function
void SimpleCallback(int value) {
//do nothing
}
//class contains a boost::signal, set callback through a public function
class App {
public:
App() : sig_()
{}
typedef boost::signal<void (int value)> SigType;
typedef std::function<void (int value)> CallbackFunType;
//connect signal to a callback function
void SetCallback(CallbackFunType callback) {
sig_.connect(callback);
}
//private: //comment this out for testing purpose.
SigType sig_; //this is the boost::signal
};
//class that has member callback function
class MyCallback {
public:
MyCallback():
val(0), app()
{}
void MemberCb(int value){
val = value;
}
void Connect() {
auto bind_fun = std::bind(&MyCallback::MemberCb, this, _1);
app.SetCallback(bind_fun); //this will not compile, no viable conversion
app.sig_.connect(bind_fun); //this is fine
app.SetCallback(SimpleCallback); //this is fine
}
private:
int val;
App app;
};
int main(int argc, char **argv) {
MyCallback my_cb;
my_cb.Connect();
return 1;
}
----------------UPDATE-----------------
Reading boost signal documentation more carefully, I learned that I can pass slot type. This solves my problem
#include <functional>
#include <boost/signal.hpp>
using namespace std::placeholders; // for _1, _2, _3...
//plain simple call back function
void SimpleCallback(int value) {
//do nothing
}
//class contains a boost::signal, set callback through a public function
class App {
public:
App() : sig_()
{}
typedef boost::signal<void (int value)> SigType;
typedef SigType::slot_type CallbackFunType;
//typedef std::function<void (int value)> CallbackFunType;
//connect signal to a callback function
void SetCallback(CallbackFunType callback) {
sig_.connect(callback);
}
//private: //comment this out for testing purpose.
SigType sig_; //this is the boost::signal
};
//class that has member callback function
class MyCallback {
public:
MyCallback():
val(0), app()
{}
void MemberCb(int value){
val = value;
}
void Connect() {
auto bind_fun = std::bind(&MyCallback::MemberCb, this, _1);
app.SetCallback(bind_fun); //using SigType::slot_type
app.sig_.connect(bind_fun);
app.SetCallback(SimpleCallback);
}
private:
int val;
App app;
};
int main(int argc, char **argv) {
MyCallback my_cb;
my_cb.Connect();
return 1;
}
Reading boost signal documentation more carefully, I learned that I can pass slot type. This solves my problem
#include <functional>
#include <boost/signal.hpp>
using namespace std::placeholders; // for _1, _2, _3...
//plain simple call back function
void SimpleCallback(int value) {
//do nothing
}
//class contains a boost::signal, set callback through a public function
class App {
public:
App() : sig_()
{}
typedef boost::signal<void (int value)> SigType;
typedef SigType::slot_type CallbackFunType;
//typedef std::function<void (int value)> CallbackFunType;
//connect signal to a callback function
void SetCallback(CallbackFunType callback) {
sig_.connect(callback);
}
//private: //comment this out for testing purpose.
SigType sig_; //this is the boost::signal
};
//class that has member callback function
class MyCallback {
public:
MyCallback():
val(0), app()
{}
void MemberCb(int value){
val = value;
}
void Connect() {
auto bind_fun = std::bind(&MyCallback::MemberCb, this, _1);
app.SetCallback(bind_fun); //using SigType::slot_type
app.sig_.connect(bind_fun);
app.SetCallback(SimpleCallback);
}
private:
int val;
App app;
};
int main(int argc, char **argv) {
MyCallback my_cb;
my_cb.Connect();
return 1;
}

Call member function of an object using pthread

How can I call the thread_ready_function into a thread as commented, using pthread ? I need to call it with the class object (In the real world the function uses attributes previously set).
MWE
#include <iostream>
#include <pthread.h>
class ClassA
{
public:
void * thread_ready_function(void *arg)
{
std::cout<<"From the thread"<<std::endl;
pthread_exit((void*)NULL);
}
};
class ClassB
{
ClassA *my_A_object;
public:
void test(){
my_A_object = new ClassA();
my_A_object->thread_ready_function(NULL);
// my_A_object->thread_ready_function(NULL);
// ^
// I want to make that call into a thread.
/* Thread */
/*
pthread_t th;
void * th_rtn_val;
pthread_create(&th, NULL, my_A_object.thread_ready_function, NULL);
pthread_join(th, &th_rtn_val);
*/
}
};
int main()
{
ClassB *my_B_object = new ClassB();
my_B_object->test();
return 0;
}
if you don't want to use C++11 or stl or boost, you must use the static key word for your member function,so that the pthread can call your member function!
example code:
#include <iostream>
#include <pthread.h>
using namespace std;
class A{
public:
static void* thread(void* args);
int parella_thread(int thread_num);
};
void* A::thread(void* args)
{
cout<<"hello world"<<endl;
}
int A::parella_thread(int thread_num)
{
pthread_t* thread_ids = new pthread_t[thread_num];
for(int i=0;i<thread_num;i++)
{
pthread_create(&thread_ids[i],NULL,thread,(void*)NULL);
}
delete[] thread_ids;
}
int main(int argc,char*argv[])
{
A test;
test.parella_thread(4);
return 0;
}

Function calls with class members?

Before I present the code which is found at the bottom of this post I would like to talk about the issue and the fix's that I do not desire. Okay basically I've created a GUI from scratch sort of and one requirement I wanted for this was allow components to have their own click executions so if i click a button or tab etc.. It would call Component->Execute(); Well normally you would do something like a switch statement of ids and if that components ID equaled n number then it would perform this action. Well that seemed kinda dumb to me and I thought there has to be a better way. I eventually tried to incorporate a feature in JAVA where you would do like Component.AddActionListener(new ActionListener( public void execute(ActionEvent ae) { })); or something like that and I thought that this feature has to be possible in C++. I eventually came across storing void functions into a variable in which could be executed at any time and modified at any time. However I hadn't noticed an issue and that was this only worked with static functions. So below you'll see my problem. I've patched the problem by using a pointer to SomeClass however this would mean having an individual function call for every class type is there no way to store a function callback to a non-static class member without doing the below strategy? and instead doing a strategy like the commented out code?
//Main.cpp
#include <iostream> //system requires this.
#include "SomeClass.h"
void DoSomething1(void)
{
std::cout << "We Called Static DoSomething1\n";
}
void DoSomething2(void)
{
std::cout << "We Called Static DoSomething2\n";
}
int main()
{
void (*function_call2)(SomeClass*);
void (*function_call)() = DoSomething1; //This works No Problems!
function_call(); //Will Call the DoSomething1(void);
function_call = DoSomething2; //This works No Problems!
function_call(); //Will Call the DoSomething2(void);
SomeClass *some = new SomeClass(); //Create a SomeClass pointer;
function_call = SomeClass::DoSomething3; //Static SomeClass::DoSomething3();
function_call(); //Will Call the SomeClass::DoSomething3(void);
//function_call = some->DoSomething4; //Non-Static SomeClass::DoSomething4 gives an error.
//function_call(); //Not used because of error above.
function_call2 = SomeClass::DoSomething5; //Store the SomeClass::DoSomething(SomeClass* some);
function_call2(some); //Call out SomeClass::DoSomething5 which calls on SomeClass::DoSomething4's non static member.
system("pause");
return 0;
}
//SomeClass.hpp
#pragma once
#include <iostream>
class SomeClass
{
public:
SomeClass();
~SomeClass();
public:
static void DoSomething3(void);
void DoSomething4(void);
static void DoSomething5(SomeClass* some);
};
//SomeClass.cpp
#include "SomeClass.h"
SomeClass::SomeClass(void)
{
}
SomeClass::~SomeClass(void)
{
}
void SomeClass::DoSomething3(void)
{
std::cout << "We Called Static DoSomething3\n";
}
void SomeClass::DoSomething4(void)
{
std::cout << "We Called Non-Static DoSomething4\n";
}
void SomeClass::DoSomething5(SomeClass *some)
{
some->DoSomething4();
}
Secondary Fix for what I'll do not an exact answer I wanted but it meets my needs for now along with allowing additional features which would have become overly complicate had this not existed.
//Component.hpp
#pragma once
#include <iostream>
#include <windows.h>
#include <d3dx9.h>
#include <d3d9.h>
#include "Constants.hpp"
#include "ScreenState.hpp"
#include "ComponentType.hpp"
using namespace std;
class Component
{
static void EMPTY(void) { }
static void EMPTY(int i) { }
public:
Component(void)
{
callback = EMPTY;
callback2 = EMPTY;
callback_id = -1;
}
Component* SetFunction(void (*callback)())
{
this->callback = callback;
return this;
}
Component* SetFunction(void (*callback2)(int), int id)
{
this->callback_id = id;
this->callback2 = callback2;
return this;
}
void execute(void)
{
callback();
callback2(callback_id);
}
}
The syntax for pointers-to-member-functions is as follows:
struct Foo
{
void bar(int, int);
void zip(int, int);
};
Foo x;
void (Foo::*p)(int, int) = &Foo::bar; // pointer
(x.*p)(1, 2); // invocation
p = &Foo::zip;
(x.*p)(3, 4); // invocation
Mind the additional parentheses in the function invocation, which is needed to get the correct operator precedence. The member-dereference operator is .* (and there's also ->* from an instance pointer).

How to call a function which belongs to a class in C++?

I am trying to call the function hello which belongs to the class program1
#include <iostream>
using namespace std;
class program1
{
program1();
~program1();
hello();
}
program1::hello()
{
cout<<"hello";
}
int main()
{
program1.hello(); //Call it like a normal function...
cin.get();
}
Names inside a class are private by default.
class program1 {
public:
program1();
~program1();
void hello() ;
};
// ...
int main(int, char **) {
program1 myProgram;
myProgram.hello();
return 0;
}
Alternatively, you can invoke a method on a temporary:
int main(int, char **) {
program1().hello();
return 0;
}
but that's probably for later in the semester.
you forgot to create an object:
int main()
{
program1 p1;
p1.hello();
}
Class definition should end with ;
Secondly, you need to instantiate class to call members on it. ( i.e., creation of an object for the class )
In C++, methods should have return type.
program1::hello(); // method should have a return type.
class members and methods are private by default, which means you cannot access them outside the class-scope.
So, the class definition should be -
class program1
{
public: // Correction 1
program1();
~program1();
void hello(); // Correction 2
};
void program1::hello() // Need to place return type here too.
{
cout<<"hello";
}
Now on creation of object for class program1, it's method hello() can be called on it.
This version is edited. (make sure you include all the body of the methods)
#include <iostream>
using namespace std;
class program1
{
public: // To allow outer access
program1();
~program1();
void hello(); // The void
}; // Don't miss this semicolon
void program1::hello() // The void
{
cout<<"hello";
}
int main()
{
program1 prog; // Declare an obj
prog.hello(); //Call it like a normal function...
cin.get();
}
I noticed that you left out return type for your hello() function.
If you want to call hello() as a member function, then as suggested you should create an object to it.
program1 prog;
prog.hello();
If you want to call it without an object, the you should use static function.
class program1
{
public: // To allow outer access
program1();
~program1();
static void hello(); // The void
}
then you can call it this way:
program1::hello();
Therefore the working code should be this way:
#include <iostream>
using namespace std;
class program1 {
public:
void hello();
}; // Don't miss this semicolon
class program2 {
public:
void static hello(); // to demonstrate static function
}; // Don't miss this semicolon
void program1::hello() {
cout << "Hello, I'm program1." << endl;
}
void program2::hello() {
cout << "Hello, I'm program2." << endl;
}
int main(void) {
program1 prog1;
prog1.hello(); // Non-static function requires object
program2::hello(); // Static function doesn't
return 0; // Return 0
}