我可以从 C++ 调用 clojure 代码吗?

Can I call clojure code from C++?(我可以从 C++ 调用 clojure 代码吗?)

本文介绍了我可以从 C++ 调用 clojure 代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为用 C++ 编写的程序编写插件.

I'm writing a plugin for a program written in C++.

插件被放置在一个特定的目录中并被主应用程序调用.我想用 Clojure 编写大部分插件(gui、计算等),但是实际的插件"需要用 C++ 编写.各种数据需要从C++传递到Clojure.

Plugins are placed in a specific dir and get called by the main application. I would like to write most of the plugin in Clojure (gui, calculations, etc) however the actual "plugin" needs to be written in C++. Various data needs to be passed from C++ to Clojure.

我该怎么做?

JNI/JNA、套接字、系统调用?(我知道的不多)

JNI/JNA, sockets, system calls? (nothing I know much about)

推荐答案

我知道这个问题很老,但也许有人觉得这很有用.

I know this question is old but maybe somebody find this useful.

#include <jni.h>       /* where everything is defined */
#include <cstring>

int main() {
    JavaVM *jvm;       /* denotes a Java VM */
    JNIEnv *env;       /* pointer to native method interface */
    JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
    JavaVMOption* options = new JavaVMOption[1];
    options[0].optionString = "-Djava.class.path=/home/raoof/.m2/repository/org/clojure/spec.alpha/0.1.143/spec.alpha-0.1.143.jar:/home/raoof/.m2/repository/org/clojure/clojure/1.9.0/clojure-1.9.0.jar";
    vm_args.version = JNI_VERSION_1_6;
    vm_args.nOptions = 1;
    vm_args.options = options;
    vm_args.ignoreUnrecognized = false;
    /* load and initialize a Java VM, return a JNI interface
     * pointer in env */
    JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
    delete options;

    jclass Clojure = env->FindClass("clojure/java/api/Clojure");
    jmethodID var = env->GetStaticMethodID(Clojure, "var", "(Ljava/lang/Object;Ljava/lang/Object;)Lclojure/lang/IFn;");
    jobject load_string = env->CallStaticObjectMethod(Clojure, var, env->NewStringUTF("clojure.core"), env->NewStringUTF("load-string"));
    jmethodID load_string_invoke = env->GetMethodID(env->GetObjectClass(load_string), "invoke", "(Ljava/lang/Object;)Ljava/lang/Object;");
    env->CallObjectMethod(load_string, load_string_invoke, env->NewStringUTF("(prn (+ 1 2 3 4 5))"));

    jvm->DestroyJavaVM();
}

然后

g++ -I/usr/lib/jvm/java-8-openjdk-amd64/include -I/usr/lib/jvm/java-8-openjdk-amd64/include/linux/ -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -ljvm clojurejvm.cpp
LD_LIBRARY_PATH=/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server ./a.out

这篇关于我可以从 C++ 调用 clojure 代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我可以从 C++ 调用 clojure 代码吗?

上一篇: Emacs - 覆盖缩进
下一篇: C++中的回调函数

基础教程推荐