(python study) C Module for using in python , in Visual Studio

Firstly, I describe to make C module in Visual Studio.

open visual studio
make project -> win32 console application
check DLL, Empty project on setting page




make new .c file and set property 
select Include directories and Library directories on the VC++ Directories page.
In my case, My installed python is located 
Include -> C:\Python33_32\include
Library -> C:\Python33_32\libs  (Caution, not LIB folder)


Notice, my compile option is release, because I have only release version lib(python32.lib),
Python32_d.lib file is not support default. 
If you compile by debug version, you rebuild python source code to debug version by CMake.

programing this source code and compile~!

...
#include "Python.h"

#pragma comment(lib, "python33.lib")          

static PyObject *
 spam_strlen(PyObject *self, PyObject *args)
{
 const char * str = NULL;
 int len = 0; 

 if(!PyArg_ParseTuple(args, "s", &str))
  return NULL;

 //main source code
 len = strlen(str);

 return Py_BuildValue("i", len);
} 

static PyMethodDef SpamMethods[] = { 
 {"strlen", spam_strlen, METH_VARARGS, "count a string length."},
 {NULL, NULL, 0, NULL} //represent end of array
};

static struct PyModuleDef spammodule = {
 PyModuleDef_HEAD_INIT,
 "spam", //name of module
 "It is test module.", //description
 -1,
 SpamMethods
};

PyMODINIT_FUNC PyInit_spam(void)
{
 return PyModule_Create( &spammodule);
}
---

rename ~.dll to spam.pyd
If module name is not matched, cannot use module, error occurred when run in python.


copy spam.pyd into python\LIB folder



In the python, programing following source and run~!

...
import spam
print( spam.strlen( "Hello world") )
---


Comments

Popular posts from this blog

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

OpenCV Stitching example (Stitcher class, Panorama)

AMP dose run on my pc?, AMP(Accelerated Massive Parallelism)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Optical Flow sample source code using OpenCV

Real-time N camera stitching Class.

OpenCV meanShiftFiltering example source code ( cpu: pyrMeanShiftFiltering, gpu:meanShiftFiltering, gpu:meanShiftSegmentation )

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

Image warping (using opencv findHomography, warpPerspective)