I think the cleanest way to solve this problem is to use the go-pointers 
library and pass in the opaque pointer from the application through to the 
go callback.

Here's a blog post I found detailing how this is done:
https://eli.thegreenplace.net/2019/passing-callbacks-and-pointers-to-cgo/



On Tuesday, October 18, 2022 at 9:50:21 PM UTC-4 David Stainton wrote:

>
> Okay here I've tried a similar solution to the go-pointers library... but 
> i had to change it a bit to fit how the C library uses the context pointer:
>
> https://git.xx.network/elixxir/ctidh_cgo/-/commit/8f02611b943c269eab5b6e888958e4d41d72cd51
>
> It builds and runs... and then panics on the "rng is nil"... not sure why. 
> So I'm going to try another solution where I change the C api slightly.
>
> I'm convinced there are many possible solutions to this and picking one is 
> a matter of deciding among a few tradeoffs.
>
>
> On Tuesday, October 18, 2022 at 6:33:11 PM UTC-4 David Stainton wrote:
>
>> Greetings cgo experts, perhaps this post might also be of some interest 
>> to cryptography people as well.
>>
>> What's the best way for a C cryptography library to receive entropy from 
>> golang?
>>
>> There exists a C cryptography library (CTIDH, it's a PQ NIKE)... I am 
>> collaborating with C programmers who are adding features to it. I maintain 
>> cgo bindings for this library. Thus far the cgo is straight forward and it 
>> works. However the C programmers recently added a constructor for private 
>> keys which takes a function pointer as an argument:
>>
>> https://codeberg.org/io/highctidh/src/branch/main/csidh.h#L50
>>
>> /*
>>  * generate a new private key using rng_callback and write the result to 
>> (priv).
>>  * (priv) is passed as (context) to the rng_callback.
>>  */
>> void csidh_private_withrng(private_key *priv, ctidh_fillrandom 
>> rng_callback);
>>
>> I did get this to work with an ugly hack where the golang constructor 
>> takes an io.Reader interface object as an argument and sets an unexported 
>> module scoped global variable to the rng/io.Reader object, guarded by a 
>> mutex, gross:
>>
>>
>> https://git.xx.network/elixxir/ctidh_cgo/-/commit/2e7fb078722decb07ab8da7fb59c8ec46fb32fd1
>>
>> But that's a really ugly hack and if called by multiple threads would 
>> result in the rng getting overwritten... which in most cases is probably 
>> fine for that to happen but seems like a bad design.
>>
>>
>>
>>
>>

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/a8b5fa3e-3ff0-45f1-8864-c169d6cafa23n%40googlegroups.com.

Reply via email to