Skip to content

Instantly share code, notes, and snippets.

@iffy

iffy/clib.nim Secret

Created January 25, 2019 05:03
Show Gist options
  • Save iffy/789a2788b0e585f8c380867616847555 to your computer and use it in GitHub Desktop.
Save iffy/789a2788b0e585f8c380867616847555 to your computer and use it in GitHub Desktop.
Nim memory debugging, trying dynamic lib, but it fails to compile on macOS
import strformat
import strutils
import sequtils
echo "clib initialized"
echo GC_getStatistics()
proc hello_echo*(message:cstring):cstring {.exportc.} =
## Echo a message back
var s_message:string = $message
result = &"{s_message} echo"
# echo &"Nim echo result: {result}"
proc stats*() {.exportc.} =
echo GC_getStatistics()
#!/bin/bash
set -e
rm -r csrc || echo
mkdir -p csrc
cp ~/lib/Nim/lib/nimbase.h csrc/
nim c -f -o:libclib.dylib --app:lib --header --nimcache:csrc clib.nim
clang++ -o test test.cpp -lclib -L.
./test
$ ./go.sh
Hint: used config file '/Users/matt/lib/Nim/config/nim.cfg' [Conf]
Hint: used config file '/Users/matt/lib/Nim/config/config.nims' [Conf]
Hint: system [Processing]
Hint: clib [Processing]
Hint: strformat [Processing]
Hint: macros [Processing]
Hint: parseutils [Processing]
Hint: unicode [Processing]
Hint: strutils [Processing]
Hint: math [Processing]
Hint: bitops [Processing]
Hint: algorithm [Processing]
Hint: sequtils [Processing]
CC: stdlib_system
CC: clib
Hint: [Link]
Hint: operation successful (30080 lines compiled; 0.661 sec total; 38.414MiB peakmem; Debug Build) [SuccessX]
Undefined symbols for architecture x86_64:
"hello_echo(char*)", referenced from:
echo(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in test-ca3c9a.o
"stats()", referenced from:
_main in test-ca3c9a.o
"NimMain()", referenced from:
_main in test-ca3c9a.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
#include <iostream>
#include "csrc/clib.h"
using namespace std;
N_CDECL(void, NimMain)(void);
std::string echo(std::string arg) {
const char* message = arg.c_str();
cout << "C++ passing message: " << message << "\n";
cout << "C++ message addr: " << (void*)message << "\n";
char* retval = hello_echo(
(char *)(message)
);
cout << "C++ retval addr : " << (void*)retval << "\n";
return std::string(retval);
}
int main(void) {
NimMain();
cout << "Hello world\n";
int i = 0;
for (i = 0; i < 10000; i++) {
std::string msg = "Hello " + std::string(i, '-');
std::string ret = echo(msg);
cout << "Got reply: " << ret << "\n";
}
stats();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment