I am trying to use Neko dlls (written in C++) with the C++ target of Haxe. I am able to call the functions in haxe but not able to pass values.
This is the C++ code -
value Hello(value h)
{
cout << val_int(h);
return val_int(1);
}DEFINE_PRIM(Hello, 1);
This is the Haxe code -
class Main
{
var load = cpp.Lib.loadLazy( "ndll" , "Hello", 1 );
static function main()
{
load(1);
}
}
It executes only if the function does not take parameters. Also, the value that is returned form the C++ function to Haxe is null.
This code actually works perfectly when I compile for the neko target, but it doesn't seem to work with the cpp target.
Any help is appreciated.
Here's the fully corrected C++ code :
#define IMPLEMENT_API
/* Will be compatible with Neko on desktop targets. */
#if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX)
#define NEKO_COMPATIBLE
#endif
#include <hx/CFFI.h>
#include <stdio.h>
/* Your hello function. */
value hello(value h)
{
printf("%i\n", val_int(h));
return alloc_int(1);
}
DEFINE_PRIM(hello, 1);
/* Main entry point. */
extern "C" void mylib_main()
{
// Initialization code goes here
}
DEFINE_ENTRY_POINT(mylib_main);
What's important is that every value given as an argument to a primitive or returned by a primitive must be of the type value. That's why your parameter and return didn't work.
val_int is used to convert a value into a native C type, so your printing code was correct. But your return was wrong : you can't return a C int type when the function expects you to return a value to Haxe. You need to create a new Haxe Int type and return it. This is done with the help of alloc_int.
Here's the Haxe part of the code as a reference :
class Main
{
static var hello = cpp.Lib.load("myLib", "hello", 1);
static function main()
{
var myReturnedInt:Int = hello(1);
}
}
A few helpful links :
Neko C FFI
Neko FFI tutorial
CPP FFI notes
In order for this to work, you'll have to add to the header of your cpp file:
#define IMPLEMENT_API
#include <hx/CFFI.h>
(instead of neko's headers)
If you want the ndll to run on both neko and hxcpp, you should also add
#define NEKO_COMPATIBLE
before the hx/CFFI.h include.
You can compile using whatever is best for you, but I recommend using a Build.xml to generate your ndll, since it will automatically add the include and lib paths correctly for hxcpp's headers. You can see an example of a very simple Build.xml here:
http://pastebin.com/X9rFraYp
You can see more documentation about hxcpp's CFFI here: http://haxe.org/doc/cpp/ffi
Related
I am working on a school project which requires to work with sheepdog. Sheepdog provides a c api which enables you to connect to a sheepdog server.
First i create c source file(test.c) with the following content :
#include "sheepdog/sheepdog.h"
#include <stdio.h>
int main()
{
struct sd_cluster *c = sd_connect("192.168.1.104:7000");
if (!c) {
fprintf(stderr, "failed to connect %m\n");
return -1;
}else{
fprintf(stderr, "connected successfully %m\n");
}
return 0;
}
then i compile with no error using the following command
gcc -o test test.c -lsheepdog -lpthread
But what i need is to use it with c++ project so i created a cpp file(test.cpp) with the following content :
extern "C"{
#include "sheepdog/sheepdog.h"
}
#include <stdio.h>
int main()
{
struct sd_cluster *c = sd_connect("192.168.1.104:7000");
if (!c) {
fprintf(stderr, "failed to connect %m\n");
return -1;
}else{
fprintf(stderr, "connected successfully %m\n");
}
return 0;
}
now, when i compiled using the following command :
g++ -o test test.cpp -lsheepdog -lpthread
I got this error :
You can't just wrap extern "C" around a header and expect it to compile in a C++ program. For example, the header sheepdog_proto.h uses an argument named new; that's a keyword in C++, so there's no way that will compile as C++. The library was not designed to be called from C++.
I agree with #PeteBecker. From a quick look around Google, I am not sure there is an easy solution. Sheepdog is using C features and names that don't port well to C++. You might need to hack sheepdog fairly extensively. For example:
move the inline functions out of sheepdog_proto.h into a new C file, leaving prototypes in their place. This should take care of the offsetof errors, e.g., discussed in this answer.
#define new not_a_keyword_new in sheepdog/sheepdog.h
and whatever other specific changes you have to make to get it to compile. More advice from the experts here.
As sheepdog was not designed to be useable from C++ you should build a tiny wrapper in C language to call the functions from sheepdog and only call the wrapper from your c++ code. Some hints to write such a wrapper:
void * is great to pass opaque pointers
extractors can help to access badly named members. If a struct has a member called new (of type T), you could write:
T getNew(void *otherstruct); // declaration in .h
and
T getNew(void *otherstruct) { // implementation in a c file
return ((ActualStruct *) otherstruct)->new;
}
Depending on the complexity of sheepdog (I do not know it) and the part you want to use, it may or not be an acceptable solution. But it is the way I would try facing such a problem.
Anyway, the linker allows mixing modules compiled in C and in C++, either in static linking or dynamic linking.
I've project where I need to distinguish files belongs to linux daemon (witten in C) and simple linux program (written in C++). Those two projects used 2 shared files (helpers_functions). Daemon and program has different logging system. Daemon write to file, program to stdout.
Problem occurs when I want to log something in common functions for both programs (inside helper_functions file). I don't want to pass via parameter, that this is program A, or program B.
I've compile files belongs to separate programs with g++ flag -D, but what can I do, when I want to log from common files? I cannot define there anything, because I don't know when I use it for program A, or when for program B.
You could add a global variable
const int iamprogram = ...;
which is defined to be PROGRAM_A in program A and PROGRAM_B in program B to solve the immediate problem. You could also make this variable directly contain the file you want to log to:
const char *program_logfile = "/path/to/logfileA";
In the long run, I suggest you to refactor your code such that the common code doesn't depend on which program it is part of. That's much more maintainable and expandable for the case where you want to use the code for a third program as well.
I'm not 100% sure if runtime dynamic linking can handle this. It would definitely work if you statically link the helper functions into each executable.
Provide a logging function with the same API in both programs. Have the library functions that want to log something call this function. They get the implementation provided by the program that's using the library.
Header file included by each program, and by the library
// common_log.h
#ifdef __cplusplus
extern "C" // for the following definition only, no opening {
#endif
// used by code that can be part of either program
void common_log(char *msg, int log_prio);
Implementation in the tty C++ program (simple logging):
#include "common_log.h"
#include <iostream>
// used by the rest of the C++ program
void simple_logger(char *msg) {
cerr << msg;
}
extern "C" void common_log(char *msg, int log_prio) {
simple_logger(msg);
}
Implementation in the daemon C program:
#include "common_log.h"
#include <stdio.h>
#include <errno.h>
static FILE *logfp;
static int log_level;
// used by daemon code
void fancy_logger(char *msg, int log_prio) {
if (log_prio < log_level)
return;
if (EOF == fputs(logfp, msg)) {
perror("failed to write log message to log file: ");
}
}
// or use linker tricks to make common_log an alias for fancy_log,
// if they both have the same signature and you don't need to do anything in the wrapper.
//extern "C" // this is already C
void common_log(char *msg, int log_prio) {
fancy_logger(msg, log_prio);
}
This requires the linker to be able to resolve undefined symbols in the library using symbols from the program that's linked against it. I think that works, similar to a library providing a weak definition of a global variable, so the main program's definition takes precedence.
If it was ok for simple_logger to also be extern "C" and have the same signature, you could just name them the same and avoid the bounce function. Or if the common function could be an alias for the program's own logging function in either of the programs, I think there are linker tricks to actually do that, instead of compiling to a single jmp instruction (tail-call optimization).
You could implement a callback for getting the program specific output. There's two benefits: no dependency from common part to application (common part defines the interface) and you can make the distinction at run time vs compile time, which gives more legroom for future development, such as changing the output via command line parameters or user interaction.
In the following example, let's refer to the common code part as "library".
library.h
typedef void (*logFunc_t)( logBuffer_t );
void setLogOutput( logFunc_t applicationLog );
library.c
logFunc_t logger; // might be good idea to initialize to an empty function, but omitted here
void setLogOutput( logFunc_t applicationLog )
{
logger = applicationLog;
}
void log( logBuffer_t data )
{
logger( data );
}
application.cpp / application.c
// here you should have the extern "C" in C++ application to ensure linkage compatibility
// I am assuming your shared code is C
extern "C" void myLogger( logBuffer_t data );
int main( int argc, char* agv[] )
{
setLogOutput( &myLogger );
// ...do your thing
return 0;
}
void myLogger( logBuffer_t data )
{
// ...log wherever
}
I have a program written in C and I need to use KDIS libraries which are written in C++. I compile my C program with automake&friends in KDevelop. How can I compile everything together?? Because I want to call some KDIS functions inside my C program.
Thank you in advance.
If you need to call C++ functions which are not declated extern "C", then you have to do so from a C++ program yourself. You can create one single C++ file in your project which wraps all the library functions you need in extern "C" functions to be used by the rest of your project. You'll have to tell autotools that you're using both C and C++. The file extensions should be enough to decide which is which.
To give you an example, consider the following mymagic.cc creating bindings for some libmagic written in C++:
#include <libmagic/magic.hh>
extern "C" {
int doMagic() {
magic::Wizard w("foo", 42);
magic::Result res = w.doMagic();
return res.getResultCode();
}
}
To the rest of your application, doMagic() would appear as just another C function. But the inside is C++, so it can use any C++ constructs you want. When you need to pass stuff from your library around, you should use pointers to opaque types. So in the header mymagic.h which is also used by your C code, you can write
struct magicValue;
int doMagic(void);
struct magicValue* createMagic(void);
void destroyMagic(struct magicValue*);
And in the mymagic.cc you'd then be more explicit:
struct magicValue {
magic::value v;
magicValue(magic::value val) : v(val) { }
};
magicValue* createMagic() {
return new magicValue(magic::value("foo"));
}
void destroyMagic(magicValue*) {
delete magicValue;
}
This link may help you understand how to mix C and C++ code in your application.
Also, look at this Stack Overflow question, I believe that's what you need.
for example I have a function in python that I want to convert to c++ (or call from c++ but I don't want to depend on python interpretor)
simple python function
//test.py
def my_sum(x,y):
print "Hello World!"
return x*x+y
I run shedskin and have
//test.cpp
#include "builtin.hpp"
#include "test.hpp"
namespace __test__ {
str *__name__;
void __init() {
__name__ = new str("__main__");
}
} // module namespace
int main(int, char **) {
__shedskin__::__init();
__shedskin__::__start(__test__::__init);
}
//test.hpp
#ifndef __TEST_HPP
#define __TEST_HPP
using namespace __shedskin__;
namespace __test__ {
extern str *__name__;
} // module namespace
#endif
ugly code and there is no my function my_sum and code depends on "builtin.hpp". is it possible to convert only function?
or
I want to call function from my c++ code something like
int sum= py.my_sum(3,5);
how can I do this?
or
maybe I can do DLL or Lib from python code that I can use in c++ code?
notice the warning that shedskin gives for this program:
*WARNING* test.py:1: function my_sum not called!
it is also mentioned in the documentation that for compilation to work, a function should be called (directly or indirectly), as it's not possible to do type inference otherwise.. how to determine the types of the arguments of my_sum, if there's not even a single call to it..? :-)
adding this, for example:
if __name__ == '__main__':
my_sum(1,1)
makes my_sum appear in the generated C++ code, which can potentially be called from another C++ program.
I have a basic solution file (.sln) where I was able to reproduce a problem I have been facing recently.
It contains 3 projects:
1.) MathTest.lib - containing methods that might cause a mathematical error, like acos(1.1).
2.) MathTestDll.dll - calls the methods from the above lib.
3.) UnitTest.exe - calls the exported method in the DLL that should cause the error.
What I'm trying to do is fairly simple:
The following code contains the _matherr() routine and should ideally link fine. The call to acos() with a value of 1.1 is invalid (invalid input) and should cause an error which should be handled by the implemented _matherr() handler. I hope I'm right about the behavior of _matherr(). Please let me know.
MathTest.lib
#include "MathTest.h"
#include <iostream>
#include <math.h>
int _matherr(_exception* _Except)
{
std::cout << _Except->name;
return -1;
}
void MathTest::ThrowMatherr(float par)
{
float result = acos(par);
std::cout << result;
}
This 'ThrowMatherr()' method will be called by the DLL as follows:
MathTestDll.dll
void MatherrCaller::CauseMatherr()
{
MathTest* mathtest = new MathTest();
mathtest->ThrowMatherr(1.1);
}
which is then exported as:
extern "C" __declspec(dllexport) void CallThisToCauseMatherr();
void CallThisToCauseMatherr()
{
MatherrCaller* caller = new MatherrCaller();
caller->CauseMatherr();
}
This exported method will be called by a simple test.
UnitTest.exe
#include <windows.h>
typedef void (*METHODTOCALL)();
int main()
{
HMODULE module = LoadLibrary((LPCSTR)"..\\Debug\\MatherrTestDll.dll");
if(module != NULL)
{
METHODTOCALL ProcAdd = (METHODTOCALL) GetProcAddress(module, (LPCSTR)"CallThisToCauseMatherr");
if (NULL != ProcAdd)
{
(ProcAdd)();
}
FreeLibrary(module);
}
return 0;
}
All methods get called fine. But the acos() method which has been passed invalid input never calls the _matherr() error handler. Please let me know how I can fix this.
I had to make the question detailed to get my point through. Please don't mind.
It is explicitly mentioned in the documentation for _matherr:
For special error handling, you can
provide a different definition of
_matherr. If you use the dynamically linked version of the C run-time
library (Msvcr90.dll), you can replace
the default _matherr routine in a
client executable with a user-defined
version. However, you cannot
replace the default _matherr routine
in a DLL client of Msvcr90.dll.
You'll need to put the override in the EXE module. Alter your unit test to accommodate this.