I am trying to do a simple proof of concept and call a very basic c++ dll from node by using ffi-napi.
It works fine when I am using methods that take/return int or char, but my attempts to return a string have failed.
c++ code, main.h:
#include <string>
#include <stdlib.h>
using namespace std;
#define EXPORT __declspec(dllexport)
extern "C" {
EXPORT string hello(string x);
EXPORT int count(int x);
}
c++ code, main.cpp:
#include "pch.h"
#include <string>
#include <stdlib.h>
#include "Main.h"
using namespace std;
string hello(string name)
{
return "Hello " + name + "! ";
}
int count(int x)
{
return x+1;
}
When I am running node code below,
import { Console } from "node:console";
var ffi = require('ffi-napi');
var ref = require('ref-napi');
export class DllTester {
LibName: string = 'D:\\temp\\DemoDll\\x64\\Debug\\DemoDll.dll';
Lib: any = null;
private setupOcrLib()
{
this.Lib = ffi.Library(this.LibName,
{'hello': [ 'string', ['string']],
'count': [ ref.types.int, [ref.types.int]]
}
);
}
count(x: number): number {
this.setupOcrLib();
console.log("Calling count");
return this.Lib.count(x);
}
hello(name: string): string {
this.setupOcrLib();
console.log("Calling hello: " + name);
return this.Lib.hello(name);
}
}
const tester = new DllTester();
console.log("Count: " + tester.count(3));
console.log("Hello: " + tester.hello("Markus"));
console.log("Count: " + tester.count(10));
I get the following console output:
Calling count
Count: 4
Calling hello: Markus
So the first call (sending int, receiving int) works fine, but the second call (sending string, receiving string) silently fails and since the second call to count is not logged, I believe my unsuccessfull call disturbs the flow.
Have tried the following:
- using char* instead of string in the dll. I then receive "something" but not readable text
- using ref-napi to set types instead of strings but demos suggest that this is not required: https://github.com/node-ffi-napi/node-ffi-napi
My understanding of c++ is limited and might have missed some part about types and pointers but this looks so simple that nothing should be able to go wrong...
Platform: windows 10, 64 bit, node v14.12.0, VS 2019 Community
Versions: "ffi-napi": "^4.0.3", "ref-napi": "^3.0.2"
Thanks for your input :-)
std::string? On the JS side, there is nothing that operates similar tousing namespace std;on the C++ side. BTW: Doing so in C++ is frowned upon, because it pollutes the namespace, but that's a different issue. - Ulrich Eckhardtstd::stringis not a universal, built-in type, likeint. Astd::stringinternals differ between C++ compiler, build settings, etc. If you want a real-world example, look at the Windows API and how it handles string data. The user creates the buffer, sends it to the API function, and the function fills the buffer. - PaulMcKenzie