{"id":1826,"date":"2025-01-16T16:35:05","date_gmt":"2025-01-16T08:35:05","guid":{"rendered":"https:\/\/www.fanyamin.com\/wordpress\/?p=1826"},"modified":"2025-01-16T16:35:05","modified_gmt":"2025-01-16T08:35:05","slug":"how-to-call-go-function-by-java-jni","status":"publish","type":"post","link":"https:\/\/www.fanyamin.com\/wordpress\/?p=1826","title":{"rendered":"How to call go function by java JNI"},"content":{"rendered":"<p>To use JNI to call the <code>CreateRole<\/code> function of the Teleport Go client, you need to expose this functionality through a Go shared library, following the steps below. The goal is to make the Go function callable from Java by wrapping it in a JNI-compatible interface.<\/p>\n<hr \/>\n<h3><strong>1. Understand the Function Signature<\/strong><\/h3>\n<p>The Go function you want to call has the signature:<\/p>\n<pre><code class=\"language-go\">func (c *Client) CreateRole(ctx context.Context, role types.Role) (types.Role, error)<\/code><\/pre>\n<ul>\n<li><strong><code>ctx context.Context<\/code><\/strong>: The context for controlling request lifetime.<\/li>\n<li><strong><code>role types.Role<\/code><\/strong>: The role to create.<\/li>\n<li><strong><code>(types.Role, error)<\/code><\/strong>: The created role or an error.<\/li>\n<\/ul>\n<h3><strong>2. Expose the Functionality with a Wrapper<\/strong><\/h3>\n<p>Create a Go wrapper function that simplifies the parameters and returns the result in a JNI-compatible format (like a C string).<\/p>\n<h4>Example Wrapper Code:<\/h4>\n<pre><code class=\"language-go\">package main\n\n\/*\n#cgo CFLAGS: -I.\n#cgo LDFLAGS: -L. -lteleport\n#include &lt;stdlib.h&gt;\n*\/\nimport &quot;C&quot;\n\nimport (\n    &quot;context&quot;\n    &quot;encoding\/json&quot;\n    &quot;github.com\/gravitational\/teleport\/api\/client&quot;\n    &quot;github.com\/gravitational\/teleport\/api\/types&quot;\n    &quot;unsafe&quot;\n)\n\n\/\/export CreateRole\nfunc CreateRole(addr *C.char, name *C.char, roleSpecJSON *C.char) *C.char {\n    addrStr := C.GoString(addr)\n    nameStr := C.GoString(name)\n    roleSpecStr := C.GoString(roleSpecJSON)\n\n    \/\/ Parse the role specification from JSON\n    var roleSpec types.RoleSpecV4\n    if err := json.Unmarshal([]byte(roleSpecStr), &amp;roleSpec); err != nil {\n        return C.CString(&quot;Error parsing role specification: &quot; + err.Error())\n    }\n\n    \/\/ Create a client\n    client, err := client.New(client.Config{\n        Addrs: []string{addrStr},\n    })\n    if err != nil {\n        return C.CString(&quot;Error creating client: &quot; + err.Error())\n    }\n    defer client.Close()\n\n    \/\/ Create the role\n    role, err := types.NewRole(nameStr, roleSpec)\n    if err != nil {\n        return C.CString(&quot;Error creating role object: &quot; + err.Error())\n    }\n\n    createdRole, err := client.CreateRole(context.Background(), role)\n    if err != nil {\n        return C.CString(&quot;Error creating role: &quot; + err.Error())\n    }\n\n    \/\/ Convert the created role to JSON\n    createdRoleJSON, err := json.Marshal(createdRole)\n    if err != nil {\n        return C.CString(&quot;Error serializing created role: &quot; + err.Error())\n    }\n\n    return C.CString(string(createdRoleJSON))\n}\n\nfunc main() {}<\/code><\/pre>\n<hr \/>\n<h3><strong>3. Compile the Go Shared Library<\/strong><\/h3>\n<p>Build the shared library (<code>.so<\/code>) with the wrapper function:<\/p>\n<pre><code class=\"language-bash\">go build -o libteleport.so -buildmode=c-shared main.go<\/code><\/pre>\n<p>This will generate:<\/p>\n<ul>\n<li><code>libteleport.so<\/code>: The shared library.<\/li>\n<li><code>libteleport.h<\/code>: The C header file to include in Java.<\/li>\n<\/ul>\n<hr \/>\n<h3><strong>4. Java Code for JNI Integration<\/strong><\/h3>\n<p>Write the Java code to load and call the shared library.<\/p>\n<h4>Define the Native Method<\/h4>\n<pre><code class=\"language-java\">public class TeleportClient {\n    static {\n        System.loadLibrary(&quot;teleport&quot;); \/\/ Loads libteleport.so\n    }\n\n    public native String createRole(String address, String name, String roleSpecJSON);\n\n    public static void main(String[] args) {\n        TeleportClient client = new TeleportClient();\n        String address = &quot;localhost:3025&quot;;\n        String name = &quot;example-role&quot;;\n        String roleSpecJSON = &quot;{\\&quot;allow\\&quot;: {\\&quot;logins\\&quot;: [\\&quot;admin\\&quot;]}, \\&quot;deny\\&quot;: {}}&quot;;\n\n        String response = client.createRole(address, name, roleSpecJSON);\n        System.out.println(&quot;Response: &quot; + response);\n    }\n}<\/code><\/pre>\n<h4>Generate JNI Header<\/h4>\n<p>Generate the JNI header file:<\/p>\n<pre><code class=\"language-bash\">javac TeleportClient.java\njavah -jni TeleportClient<\/code><\/pre>\n<p>This creates a <code>TeleportClient.h<\/code> file. Ensure the method signature matches the Go <code>CreateRole<\/code> function.<\/p>\n<hr \/>\n<h3><strong>5. Link JNI Header with Go<\/strong><\/h3>\n<p>The generated JNI header will define a function signature like this:<\/p>\n<pre><code class=\"language-c\">JNIEXPORT jstring JNICALL Java_TeleportClient_createRole\n  (JNIEnv *, jobject, jstring, jstring, jstring);<\/code><\/pre>\n<p>Ensure your Go code wraps this method signature if necessary.<\/p>\n<hr \/>\n<h3><strong>6. Run the Java Program<\/strong><\/h3>\n<ol>\n<li>Ensure the <code>libteleport.so<\/code> is in your library path:\n<pre><code class=\"language-bash\">export LD_LIBRARY_PATH=.<\/code><\/pre>\n<\/li>\n<li>Run the Java program:\n<pre><code class=\"language-bash\">java TeleportClient<\/code><\/pre>\n<\/li>\n<\/ol>\n<hr \/>\n<h3><strong>Considerations<\/strong><\/h3>\n<ul>\n<li><strong>Error Handling<\/strong>: Ensure all errors are handled and returned as meaningful strings.<\/li>\n<li><strong>Role Specification<\/strong>: Pass the <code>roleSpecJSON<\/code> in a format expected by the Go wrapper.<\/li>\n<li><strong>Memory Management<\/strong>: Free memory allocated by <code>C.CString<\/code> using <code>C.free<\/code> if needed to avoid memory leaks.<\/li>\n<li><strong>Platform<\/strong>: Ensure the library is compiled for the correct platform (Linux, macOS, or Windows).<\/li>\n<\/ul>\n<p>Would you like further assistance with any specific part of this setup?<\/p>\n","protected":false},"excerpt":{"rendered":"<p>To use JNI to call the CreateRole function of the Teleport Go client, you need to expose this functionality through a Go shared library, following the steps below. The goal is to make the Go function callable from Java by wrapping it in a JNI-compatible interface. 1. Understand the Function Signature The Go function you [&hellip;] <a class=\"read-more\" href=\"https:\/\/www.fanyamin.com\/wordpress\/?p=1826\" title=\"Permanent Link to: How to call go function by java JNI\">&rarr;Read&nbsp;more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-1826","post","type-post","status-publish","format-standard","hentry","category-5"],"_links":{"self":[{"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/1826"}],"collection":[{"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1826"}],"version-history":[{"count":1,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/1826\/revisions"}],"predecessor-version":[{"id":1827,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=\/wp\/v2\/posts\/1826\/revisions\/1827"}],"wp:attachment":[{"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1826"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1826"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.fanyamin.com\/wordpress\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1826"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}