C 함수가 부동을 허용하도록 선언하면 컴파일러는 int를 건네 주면 불평하지 않습니다.
#include <stdio.h>
float f(float x) {
return x+1;
}
int main() {
int i=1;
printf ("%f", f(i));
}
파이썬 모듈 버전 iorf.c :
#include <Python.h>
static PyObject *IorFError;
float f(float x) {
return x+1;
}
static PyObject *
fwrap(PyObject *self, PyObject *args) {
float in=0.0;
if (!PyArg_ParseTuple(args, "f", &in))
return NULL;
return Py_BuildValue("f", f(in));
}
static PyMethodDef IorFMethods[] = {
{"fup", fwrap, METH_VARARGS,
"Arg + 1"},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initiorf(void)
{
PyObject *m;
m = Py_InitModule("iorf", IorFMethods);
if (m == NULL)
return;
IorFError = PyErr_NewException("iorf.error", NULL, NULL);
Py_INCREF(IorFError);
PyModule_AddObject(m, "error", IorFError);
}
setup.py :
from distutils.core import setup, Extension
module1 = Extension('iorf',
sources = ['iorf.c'])
setup (name = 'iorf',
version = '0.1',
description = 'This is a test package',
ext_modules = [module1])
예 :
예를 들어,이 프로그램은 응답 2.000000 생산
03:21 $ python
Python 2.7.10 (default, Jul 30 2016, 18:31:42)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import iorf
>>> print iorf.fup(2)
3.0
>>> print iorf.fup(2.5)
3.5
참고 : 쉽게 읽을 수 있도록 질문을 편집했습니다. 당신이 내가 바꾼 것을 좋아하지 않는다면, 당신의 질문이 내 것이 아니기 때문에 그것을 자유롭게 되돌릴 수 있습니다. – immibis
아마도'PyObject'로 작업하고 숫자로 작업하기 위해 [Number Protocol] (https://docs.python.org/2/c-api/number.html)을 사용하고 싶을 것입니다. 예를 들어,'float'을 강요 할 필요가 있다면'PyObject'에서'PyNumber_Float'를 호출 할 수 있습니다. – mgilson