# Segfault when invoking Julia callback function from C

**URL:** <https://discourse.julialang.org/t/segfault-when-invoking-julia-callback-function-from-c/79541>\
**Category:** General Usage\
**Tags:** question, ccall, debug, struct, c\
**Created:** [April 15, 2022, 4:38pm UTC](https://discourse.julialang.org/t/segfault-when-invoking-julia-callback-function-from-c/79541 "2022-04-15T16:38:23Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![Octogonapus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/octogonapus/32/9489_2.png) [@Octogonapus](https://discourse.julialang.org/u/Octogonapus)\
**Post date:** [April 20, 2022, 3:51pm UTC](https://discourse.julialang.org/t/segfault-when-invoking-julia-callback-function-from-c/79541/11 "2022-04-20T15:51:50Z")

</div>

Thanks to Valentin for meeting with me offline. We arrived at a final solution to this problem:

Declare a callback this way:

```julia
struct Message
	error_code::Cint
	return_code::Cint
	session_present::Cuchar
end

callback = ForeignCallbacks.ForeignCallback{Message}() do msg
	# actual callback impl in here
	return nothing
end

function on_connection_complete(connection::Ptr{aws_mqtt_client_connection}, error_code::Cint, return_code::Cint, session_present::Cuchar, userdata::Ptr{Cvoid})
	# convert and then load the pointer because this function must be type-stable
	token = Base.unsafe_load(Base.unsafe_convert(Ptr{ForeignCallbacks.ForeignToken}, userdata))
	ForeignCallbacks.notify!(token, Message(error_code, return_code, session_present))
	return nothing
end

```

Store the `user_data` this way:

```julia
token = Ref(ForeignCallbacks.ForeignToken(callback))
Base.unsafe_convert(Ptr{Cvoid}, token) # this is the user_data

```

Then you can create the callback C function:

```julia
on_connection_complete_cb = @cfunction(on_connection_complete, Cvoid, (Ptr{aws_mqtt_client_connection},Cint,Cint,Cuchar,Ptr{Cvoid}))

```

Relevant variables like `token` and `on_connection_complete_cb` must be `GC.@preserve`-ed while in use.

---

_[View the full topic](https://discourse.julialang.org/t/segfault-when-invoking-julia-callback-function-from-c/79541)._
