Jul-11-2019, 07:15 PM

I'm trying to run a basic C/Python API, I am using Python3.6
https://docs.python.org/3.6/extending/em...n-overview
My Python File Looks like
import numpy as np #import random class Multiply: def __init__(self): self.x = 2 self.y = 2 self.a = 0 def multiply(self): self.a = self.x * self.y print("Result of: {} * {}".format(self.x,self.y)) return self.a
My C File Looks Like
#include </usr/include/python3.6m/Python.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pClass; PyObject *pValue, *pDict, *pInstance; int i, arg[2]; Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); pName = PyUnicode_DecodeFSDefault("with_numpy_import"); pModule = PyImport_Import(pName); pDict = PyModule_GetDict(pModule); pClass = PyDict_GetItemString(pDict, "Multiply"); Py_DECREF(pName); if (PyCallable_Check(pClass)){ pInstance = PyObject_CallObject(pClass, NULL); } if( argc > 4 ){ for (i = 0; i < argc - 4; i++){ arg[i] = atoi(argv[i + 4]); } pValue = PyObject_CallMethod(pInstance, argv[3], "(ii)", arg[0], arg[1]); }else{ pValue = PyObject_CallMethod(pInstance, "multiply", NULL); } if(pValue != NULL){ printf("Return of call : %d\n", PyLong_AsLong(pValue)); Py_DECREF(pValue); }else{ PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pDict); Py_DECREF(pInstance); Py_DECREF(pClass); Py_Finalize(); //////// Start Over //////// Py_Initialize(); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); pName = PyUnicode_DecodeFSDefault("with_numpy_import"); pModule = PyImport_Import(pName); return 0; }
Why do I get a segmentation error when I import numpy? I can import random and it runs perfectly fine after I comment out import numpy. I have observed that this segmentation error occurs when I use modules that have been brought in with pip.
Is it safe to assume I can run Py_Initialize(); and Py_Finalize(); multiple times in one program?
Please advise.
