On Sun, 30 Sep 2018 at 17:55, Simon Ritchie <simonritchie...@gmail.com> wrote:
>
> Aagh!  I misunderstood the question.  Apologies for that.
>

I could have phrased the question more clearly also, sorry.


> There may still be a grain of usefulness in my answer.  There are limits to 
> the complexity of the C code that you can call with cgo.  (It’s even worse if 
> you are calling C++, as I was.)  You can magic away a lot of those problems 
> by writing an extra layer of C that hides the complexities.
>
> However, this probably involves having make around to bind everything 
> together.  I agree that this is a nuisance, because your user may not have 
> make, particularly if they are using Windows.  There is a version of gnu make 
> available for that, but using it just led me to a different world of pain.
>

I found a workaround finally.   Basically:
- in package A, when #including f.h via cgo, I add directive #cgo -DA
- in f.h, I only declare the functions if A is defined
#ifdef A
void f();
#endif
- in f.h, I put a pointer to f in a struct.
typedef struct S {
   void (*f)();
} S;

this struct def is not guarded by the #ifdef
- I populate the fn pointer in package A at runtime for instances of struct S.

Then in package B
- I pass the *C.S struct to C via cgo function call.
- I #include "f.h" from package A without -DA
- I pass the *C.S struct to C via cgo function call, and get the
function pointers out of it to call.

Everything builds and runs fine without link errors.



> Have you considered having two separate pieces of software, one in C and one 
> in Go and linking them together with grpc?  That would allow you to ship your 
> solution as two binaries.
>

Yes, but in this case the shared C functionality is tiny, <100LOC it
would be a shame.  Also, ironically enough, the end goal of the
contorted cgo usage above is to bypass cgo->go at runtime for a very
particular use case which needs it (definitely not recommended in
general).  It would be silly to make a thin C shim and distribute
separately as an external C dependency for the purpose of using more
pure Go and less cgo :)

Thanks in any event for your help, it was also informative to me.

Scott



> --
> You received this message because you are subscribed to a topic in the Google 
> Groups "golang-nuts" group.
> To unsubscribe from this topic, visit 
> https://groups.google.com/d/topic/golang-nuts/ruLltGrPWBg/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to 
> golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



-- 
Scott Cotton
http://www.iri-labs.com

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to