www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Create a wrapper around larger c-libraries

reply Alain De Vos <devosalain ymail.com> writes:
I'm currenlty experimenting about binding to C.
I have :
C-library:

mylib.h:
```
void libprintme(char *s);
```

mylib.c:
```
#include <stdio.h>
#include "mylib.h"
void libprintme(char *s){printf("%s",s);}
```

main.d:
```
extern(C)  nogc nothrow {
	void libprintme(char *s);
     alias pprintme=void function(char *s);
     __gshared pprintme cprintme=&libprintme;

}

extern(D) {
	void dprintme(string ds){
		alias dstring=string;
		alias cstring=char *;
		import std.conv: to,castFrom;
		cstring cs=castFrom!dstring.to!cstring(ds);
		(*cprintme)(cs);
		import core.stdc.stdio: printf;
		printf("World");
	}
```

Can this procedure be used for larger C-libraries ?
What is good , what is bad , what can be better. Feel free to 
elaborate ?

(It's the C-preprocessor with macro expansion which gives me 
sometimes a bit of a headache.)
Apr 24 2022
next sibling parent Alain De Vos <devosalain ymail.com> writes:
```
void main(){dprintme("Hello\n");}
}
```
Apr 24 2022
prev sibling parent user1234 <user1234 12.de> writes:
On Sunday, 24 April 2022 at 15:13:15 UTC, Alain De Vos wrote:
 I'm currenlty experimenting about binding to C.
 I have :
 C-library:

 mylib.h:
 ```
 void libprintme(char *s);
 ```

 mylib.c:
 ```
 #include <stdio.h>
 #include "mylib.h"
 void libprintme(char *s){printf("%s",s);}
 ```

 [...]


 Can this procedure be used for larger C-libraries ?
 What is good , what is bad , what can be better. Feel free to 
 elaborate ?

 (It's the C-preprocessor with macro expansion which gives me 
 sometimes a bit of a headache.)
Why not just ```d extern(C) nogc nothrow { void libprintme(char *s); alias cprintme = libprintme; } ``` ? The function pointer looks totally superfluous to me.
Apr 24 2022