从C向GenServer发送消息

时间:2019-09-11 16:39:35

标签: c erlang elixir erl-interface

如何将消息发送到远程Elixir GenServer,然后使用C Erlang Interface接收呼叫结果?

我想在C中运行类似于

{result1, result2} = GenServer.call(MyModule.NodeName, {:dothing, "blah"})

这是我到目前为止所拥有的。它编译并连接到远程服务器并运行ei_reg_send而不引起错误,但是远程服务器未收到响应。 (我打开了一个记录器,所以我知道电话何时接通。)

#include <erl_interface.h>
#include <ei.h>

#define COOKIE "cookieval"
#define HOST "name@host"

int main() {
  ei_init();
  ei_cnode ec;
  int n = 0;
  int sockfd;
  int self;
  if((self = ei_connect_init(&ec, "nss", COOKIE, n++)) < 0) {
    return 1;
  }
  if((sockfd = ei_connect(&ec, HOST)) < 0) {
    return 2;
  }

  ei_x_buff request;
  ei_x_new(&request);
  ei_x_format(&request, "{dothing, ~a}", "blah");
  if(ei_reg_send(&ec, sockfd, "MyModule.NodeName", request.buff, request.index) < 0) {
    return 3;
  }
  ei_x_free(&request);
  // code makes it to here, but there's no indication that the genserver was called
  return 0;
}

2 个答案:

答案 0 :(得分:3)

您无法在C节点中执行GenServer.call/2。至少不是直接的,因为这不是公共API,在这种情况下,消息的外观是这样的(不是变化很大,但是您不能依靠它)。相反,您可以做的是发送常规消息并在handle_info内进行处理。

答案 1 :(得分:0)

指出,直接从C调用具有预定名称的GenServer比预期的要困难得多。我最后要做的是在Elixir中创建一个模块函数,该函数调用GenServer本身并将结果返回给调用方。然后,我使用RPC函数在C语言中对此进行了接口。

  ei_x_buff request;                                                               
  ei_x_new(&request);                                                              
  ei_x_format_wo_ver(&request, "[~s]", "My Argument");                                      
  ei_x_buff response;                                                              
  ei_x_new(&response);                                                             
  ei_rpc(&ec, sockfd, "Elixir.MyModule", "dothing", request.buff, request.index, &response);

请参见http://erlang.org/doc/man/ei_connect.html#ei_rpc

请注意,ei_rpc不会在其响应缓冲区中返回“版本魔幻数字”,但是ei_rpc_from 确实会返回

相关问题