How can you pass a char * to nim, ive been trying for a while but i keep getting segfault.
if i use:
proc read_csv(fpx: cstring): void {.exportc.} =
let fp: string = cast[string](fpx)
var s = newFileStream(fp, fmRead)
if s == nil:
echo "file not found"
return
then there's a segfault at newFileStream
if i use
proc read_csv(fp: string): void {.exportc.} =
var s = newFileStream(fp, fmRead)
if s == nil:
echo "file not found"
return
then the first 15 chars get truncated, but i still also get a segfault at newFileStream
i tried calling the function from c with read_csv("/path/to/csv");
if i run the nim file instead of compiling to c it works.
Also i found out that if i hardcode the value i get a segfault here STRING_LITERAL(TM_xgSOGG8fvQlwPH9bPyp9bbTg_6, "path_here", 36);
thx
First way is correct, except conversion from cstring to string should be made with $.
proc read_csv(fpx: cstring): void {.exportc.} =
let fp = $fpx
var s = newFileStream(fp, fmRead)
if s == nil:
echo "file not found"
return
if it helps this is the valgrind output
==9355== Process terminating with default action of signal 11 (SIGSEGV)
==9355== Access not within mapped region at address 0x0
==9355== at 0x665CA1B: lowGauge_3mwQtFaBTgevFrybZdgUNw (stdlib_system.c:1380)
==9355== by 0x6664A53: prepareForInteriorPointerChecking_Zqr3EQAAcehIfp3uSECEuQsystem (stdlib_system.c:1418)
==9355== by 0x6664A53: collectCTBody_zoTIuavlrCHyw3B8MBaLJA_2 (stdlib_system.c:4046)
==9355== by 0x6664BF7: collectCT_zoTIuavlrCHyw3B8MBaLJA (stdlib_system.c:4115)
==9355== by 0x6664ED8: rawNewObj_QBPo5VW2O56Eeh8hPbQ7Pg (stdlib_system.c:4210)
==9355== by 0x666512F: newObjNoInit (stdlib_system.c:4226)
==9355== by 0x66651B3: rawNewStringNoInit (stdlib_system.c:4243)
==9355== by 0x6665251: toNimStr (stdlib_system.c:4707)
==9355== by 0x665A7AB: read_csv (fib.c:335)
==9355== by 0x6658C39: first_func (fib.c:22)
==9355== by 0x4E9B9E: PyCFunction_Call (in /home/x/x/venv/bin/python3.5)
==9355== by 0x524413: PyEval_EvalFrameEx (in /home/x/x/venv/bin/python3.5)
==9355== by 0x52D2E2: ??? (in /home/x/x/venv/bin/python3.5)
and this is my c code
#include "nimcache/fib.h"
#include <stdio.h>
#include <Python.h>
static PyObject* first_func(PyObject* self, PyObject* args)
{
char * value;
if (!PyArg_ParseTuple(args, "s", &value))
return NULL;
read_csv("/home/x/Downloads/x.csv");
return Py_BuildValue("f", 1.1);
}
ok fixed i had to call NimMain(); this fixed everything
PyMODINIT_FUNC
PyInit_fib(void)
{
NimMain();
return PyModule_Create(&nim_module);
}