Linking D and Obj-C code into a Cocoa app proper? (Mac)

Michel Fortin michel.fortin at michelf.com
Tue Oct 5 11:05:23 PDT 2010


On 2010-10-05 10:02:45 -0400, Heywood Floyd <soul8o8 at gmail.com> said:

> But, sometimes I get reeeaally weird bugs. I had one bug where if I 
> added an empty function to a class in D I got EXC_BAD_ACCES (segfault). 
> An empty function! Ie "void f(){}". Remove the function--it works. In 
> the debugger, I got the impression maybe the stack has got messed up, 
> but I don't know, the debugger just shows assembler code, and I don't 
> have the proper skills.

It's hard to say without further details, but it could be that you're 
not recompiling everything that uses the class where you add a 
function. Unlike in Objective-C, adding a function to a D class breaks 
most compiled code that uses that class (because you're adding an 
offset to the virtual function table), so you need to recompile every D 
module that uses that class (or a derived class).

Note that this is totally unrelated to having Objective-C code in the 
same program.


> This got really frustrating, needless to say, so I started playing 
> around with the build settings. I switched from using LLVM 1.5 (for the 
> obj-c code) to gcc 4.2. And now it magically seems to work!

Are you using D for Xcode? By doing that you basically force everything 
to be recompiled, which solves problem described above.


> [...]
> 
> == Question ==
> How do you make D code and Obj-C code coexist? That is, I want to write 
> a Cocoa-app that is mostly written in D, and with a little "glue"-code 
> in Objective-C. How do you set that up? Is it even supposed to be 
> possible?

It is totally possible, and not that hard. Communicating via `extern 
(C)` functions should work well.


> (And what could the bug above be? I know LLVM does link-time 
> optimizations, and even run-time optimizations. Could it be that it 
> messes things up?)

I doubt LLVM optimizations have anything to do with your problem. 
Things to keep in mind when mixing Objective-C:

1. Apple's Objective-C GC isn't supported by D, so you it's probably 
safer to use manual memory management (retain/release) on the 
Objective-C site.

2. Exceptions are not compatible between the two runtimes. Throwing can 
cause unexpected results when it unwinds stack frames in the other 
language.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d-learn mailing list