1

I'm a complete beginner at C++ and have been trying to access a C++ function from Python using a DLL through ctypes. I always get the error AttributeError: function 'my_function' not found when running my code.

Header.h

#pragma once

int my_function(void);

Source.cpp

#include "Header.h"

int my_function(void)
{
    return(17); //test
}

ctypesTest.py

import ctypes

if __name__ == "__main__":

    mydll = ctypes.CDLL("MyDLL.dll")

    print(mydll.my_function())

Every time I run the Python script I get the attribute error.

I only need values out of my intended function.

Wock
  • 53
  • 6
  • 1
    Maybe this is because you are missing [`extern "C"`](https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c) around the function declaration? – Mikel Rychliski Apr 17 '20 at 03:24
  • 2
    You also may need to explicitly export the function with `__declspec(dllexport)`. I don't think Windows exports functions from DLLs by default. – Mikel Rychliski Apr 17 '20 at 03:27
  • @MikelRychliski Thank you very much. When I implemented both of your suggestions the program worked. I'd been puzzling over this for hours. – Wock Apr 17 '20 at 03:40
  • This page has some good info for Windows vs Linux too: http://wolfprojects.altervista.org/articles/dll-in-c-for-python/ – BigRed118 Apr 17 '20 at 03:48

1 Answers1

2

@Mikel Rychliski answered my question.

Header.h

#pragma once

#define DllExport __declspec( dllexport )

extern "C"
{
    __declspec(dllexport) int my_function(void);
}
Wock
  • 53
  • 6