www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - D to C++ DLL

reply "Harpo" <roederharpo hushmail.com> writes:
Hello all! I am having trouble with using a c++ shared object 
file with D.
I am running Linux Mint 32 bit. I am using the 32 bit version of 
DMD.
For some reason any extra variables I pass to the C++ function 
have the value 0.
Even when I specifically pass it something else.

------------------------------------------------

D source:

import core.stdc.stdio;
import core.stdc.stdlib;
import core.sys.posix.dlfcn;

int main() {

	void *lh = dlopen("libdll.so", RTLD_LAZY);

	extern(C) long function(long y, long x) fn = cast(long 
function(long y, long x))dlsym(lh, "dll");

	fn(1, 71);

	return 0;
}

C++ source:

#include <stdio.h>

extern "C" long dll(long y, long x) {
	
	if(y == 0){
		//int myint = (int) x;
	//	printf("%c", myint);
		printf("test1: ");
		printf("%ld", x);
	}
	else if(y == 1){
		printf("test2: ");
		printf("%ld", x);
	}
	else if(y == 2){
		printf("test3: ");
  		//return getchar();
	}
   return 0;
}

Compile script:

g++ -c dll.cpp -fpic
g++ -shared -o libdll.so dll.o

dmd -c main.d
dmd main.o -L-ldl -L-rpath=.
./main

-------------------------------

Does anyone here know why this is the case, or how I can fix it?
Thanks!
Mar 13 2014
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
I didn't look closely, but since you used the "long" type my 
guess is that's the problem. long in D is always 64 bit, but in C 
is sometimes 32 bit and sometimes 64 bit.

On the D side, instead of writing "long", import 
core.stdc.config; and use c_long.

Or just use int on both sides, that should work too.
Mar 13 2014
prev sibling parent reply "FreeSlave" <freeslave93 gmail.com> writes:
long in D and long in C++ are different types. You should use 
c_long from core.stdc.config to interface with C/C++ functions.
Mar 13 2014
parent "Harpo" <roederharpo hushmail.com> writes:
Perfect Thanks!
Mar 13 2014