Piyush
Piyush

Reputation: 65

Is it possible to call a C Function by reference from python??

I am a beginner in python and I need to test a C function which is being called by reference.

Here is my C File : myfile.c

#include<stdio.h>

int my_function(int *x)
{
int A;
printf("enter value of A");
scanf("%d",&A);
*x = 10 * A; // this sets the value to the address x is referencing to
 return 0; 
}

now, my python script should call my_function() and pass the argument so that I can check and verify the result.

something like :

result = self.loaded_class.my_function(addressOf(some_variable))

self.assertEqual(some_variable,10)

Is this possible ?? how can i achieve this. And I am writing scripts in python for auto tests , not using interactive python.

Upvotes: 2

Views: 294

Answers (2)

Lauritz V. Thaulow
Lauritz V. Thaulow

Reputation: 50995

If you compile your file as a shared library or dll (I don't know how to do that), you can use ctypes like this (assuming it's a dll for this example):

import ctypes as ct

mylib = ct.cdll.myfile
c_int = ct.c_int(0)
mylib.my_function(ct.byref(c_int))
print c_int.value

Upvotes: 2

che
che

Reputation: 12263

You can write a Python interface for C function, a simple example is in Python doc. However, if all you want to do is test C function, you're probably better of with a C/C++ testing framework such as Google Test.

Upvotes: 1

Related Questions