C에서 C++ 코드 호출 2 본문

Programming/C++

C에서 C++ 코드 호출 2

halatha 2011. 5. 25. 03:35
출처: http://yesarang.tistory.com/69
2011/05/24 - [Programming/C++] - C에서 C++ 코드 호출

//	callable.h
#ifndef	_CALLABLE_H
#define	_CALLABLE_H

#ifdef	__cpluscplus
extern "C"	{
#endif

void* UsefulCppClassWrappingFunction(void* pInst);

#ifdef	__cplusplus
}
#endif

#endif

//	callable.cpp
#include <iostream>
#include "c2cpp.h"

using namespace	std;

extern "C" {

	void* UsefulCppClassWrappingFunction(void* pInst)
	{
		cout << "UsefulCppClassWrappingFunction() called" << endl;
		UsefulCppClass*	pInstance	=	static_cast<UsefulCppClass*>(pInst);
		pInstance->DoSomeAction();

		return	NULL;
	}
};

//	c2cpp.c
#include <stdio.h>
#include <pthread.h>
#include "callable.h"

int main(void)
{
	pthread_t	thrd;
	int	nr;
	void*	pInst;
	//	how can we create UsefulCppClass instance?

	nr	=	pthread_create(&thrd, NULL, &UsefulCppClassWrappingFunction, pInst);
	pthread_join(thrd, &pData);

	return	0;
}

//	callable.h
//	same as above

//	callable.cpp
#include <iostream>
#include "c2cpp.h"

using namespace	std;

extern "C" {
	void* CreateUsefulCppClass(char* name)
	{
		return	new UsefulCppClass(name);
	}

	void* UsefulCppClassWrappingFunction(void* pInst)
	{
		cout << "UsefulCppClassWrappingFunction() called" << endl;
		UsefulCppClass*	pInstance	=	static_cast<UsefulCppClass*>(pInst);
		pInstance->DoSomeAction();

		return	NULL;
	}
};

//	c2cpp.c
#include <stdio.h>
#include <pthread.h>
#include "callable.h"

int main(void)
{
	pthread_t	thrd;
	int	nr;
	void*	pInst	=	CreateUsefulCppClass("01");
	void*	pData;

	nr	=	pthread_create(&thrd, NULL, &UsefulCppClassWrappingFunction, pInst);
	pthread_join(thrd, &pData);

	return	0;
}

/*
$ g++ -c callable.cpp
$ gcc -c c2cpp.c
c2cpp.c: In function ‘main’:
c2cpp.c:9: warning: initialization makes pointer from integer without a cast
$ g++ -o c2cpp c2cpp.o callable.o -lpthread
$ ./c2cpp 
UsefulCppClassWrappingFunction() called
01: I'm doing some useful job. step #1
01: I'm doing some useful job. step #2
01: I'm doing some useful job. step #3
01: I'm doing some useful job. step #4
01: I'm doing some useful job. step #5
01: Exiting...
*/
Comments