extern C: Transition C libraries to D libraries

Robert Fraser fraserofthenight at gmail.com
Mon May 14 03:09:44 PDT 2007


Wow; that is a good idea! I'm currently working on a library in D that I want to make available to many platforms, including C, and something like that would be quite helpful.

While we're on the subject of adding extern declarations, I'd also like to propose an extern(Java) or extern(JNI), which could take something like this:

# module org.example.ClassName;
# 
# extern(Java):
#     void foo(int x) { ... }

... and turn it into...

# version(Windows)
#     extern(Windows):
# else
#     extern(C):
# 
# void Java_org_example_ClassName_foo__I(JNIEnv* env, jobject obj, jint foo) { ... }

Obviously, most of the more advanced features of the JNI would need to be explicitly dealt with, but that would work for simpler methods maybe.

- Fraser

Traveler Hauptman Wrote:

> I think there is a place for using D to code libraries meant to be 
> accessed by other languages using the C ABI as the common denominator.
> My present goal is to rewrite any existing library in the D language, 
> with a minimum of "extra glue" lines. More compact and maintainable code 
> would be the ideal result.
> 
> I have some ideas along these lines I'd like comments on. It might exist 
> or it might be a feature request.
> 
> ---
> D deals with namespaces better than C. Inferred struct properties are 
> nice too. I'd like to take advantage of these.
> 
> A common C construct is:
> 
> <code>
> typedef struct {
>    int m_property;
> } Foo;
> 
> void foo_namespace_member1(Foo* this, ...);
> void foo_namespace_set_property(Foo* this, ...);
> int foo_namespace_get_property(Foo* this);
> </code>
> 
> I can wrap the above code with extern(C) and compile the library using 
> D, but it would look a lot better (to me) using D constructs:
> 
> <code>
> extern (C_Better) "foo_namespace_" {
> struct Foo {
>    int m_property;
>    void member1(...){...}
>    void property(int in_val){...}
>    int property(){...}
> }
> }
> </code>
> 
> Automagic needed includes:
>    Members of extern(C) structs are not D mangled.
>    Adding *this to the C parameter list.
>    Prefixing namespace info to the C function names
>    Mangling "get" and "set" into property function C names.
> 
> 
> Does this make sense to anyone? Is it a reasonable idea? Useful to 
> anyone else?
> 




More information about the Digitalmars-d mailing list