Skip to content

Instantly share code, notes, and snippets.

@Alseidon
Created March 22, 2023 12:19
Show Gist options
  • Save Alseidon/8ea03a87464fea4ef9d8272b35be2b91 to your computer and use it in GitHub Desktop.
Save Alseidon/8ea03a87464fea4ef9d8272b35be2b91 to your computer and use it in GitHub Desktop.
Internal error when wrapping ccall in a function -- Pluto.jl
### A Pluto.jl notebook ###
# v0.19.22
using Markdown
using InteractiveUtils
# ╔═╡ 88a02699-a910-4a42-a8e9-960009685980
using Libdl
# ╔═╡ da477a65-5706-4385-8207-aa8bbdfc4141
md"## Setup"
# ╔═╡ 5834f232-cd72-45ab-b198-327146e6bcc6
function compile_c_func(code)
run(pipeline(`echo $code`, "test_file.c"))
run(`gcc -shared -fPIC test_file.c -o test_file.so`)
tf = Libdl.dlopen("./test_file.so")
funcsym = Libdl.dlsym(tf, :func)
return funcsym, tf
end
# ╔═╡ cce5a2a3-6c46-45d0-a53f-e19d020b31fb
function call_c_func(funcsym, val)
ccall(
funcsym,
Cint,
(Cint,),
val
)
end
# ╔═╡ cd540a81-9758-4353-b1f1-5e6e54475ec9
md"## Direct ccall"
# ╔═╡ 15ae119f-a190-413e-b499-dc9a4560112c
c_code_1 = "int func(int a) { return a; }"
# ╔═╡ 6f51922d-92d1-49c5-8f20-9ae70e4efa46
begin
funcsym_1, tf_1 = compile_c_func(c_code_1)
res_1 = ccall(
funcsym_1,
Cint,
(Cint,),
1
)
Libdl.dlclose(tf_1)
println(res_1)
end
# ╔═╡ 40b6a076-ab4b-4c2d-992a-39bb676f864b
c_code_2 = "int func(int a) { return a*2; }"
# ╔═╡ 2e0a0d14-9b69-4148-b3c5-be9886d7d144
begin
funcsym_2, tf_2 = compile_c_func(c_code_2)
res_2 = ccall(
funcsym_2,
Cint,
(Cint,),
1
)
Libdl.dlclose(tf_2)
println(res_2)
end
# ╔═╡ 06f207f2-25c2-4f74-8c09-2eeb38651e6f
md"## Using ccall in function"
# ╔═╡ 8af4c3ea-9185-4ff7-a4fc-8deee7121eea
begin
funcsym_3, tf_3 = compile_c_func(c_code_1)
res_3 = call_c_func(funcsym_3, 1)
Libdl.dlclose(tf_3)
println(res_3)
end
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
Libdl = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.8.5"
manifest_format = "2.0"
project_hash = "7b70172a2edbdc772ed789e79d4411d7528eae86"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
"""
# ╔═╡ Cell order:
# ╟─da477a65-5706-4385-8207-aa8bbdfc4141
# ╠═88a02699-a910-4a42-a8e9-960009685980
# ╠═5834f232-cd72-45ab-b198-327146e6bcc6
# ╠═cce5a2a3-6c46-45d0-a53f-e19d020b31fb
# ╟─cd540a81-9758-4353-b1f1-5e6e54475ec9
# ╠═15ae119f-a190-413e-b499-dc9a4560112c
# ╠═6f51922d-92d1-49c5-8f20-9ae70e4efa46
# ╠═40b6a076-ab4b-4c2d-992a-39bb676f864b
# ╠═2e0a0d14-9b69-4148-b3c5-be9886d7d144
# ╟─06f207f2-25c2-4f74-8c09-2eeb38651e6f
# ╠═8af4c3ea-9185-4ff7-a4fc-8deee7121eea
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment