Using Cython to expose functionality to another application

╄→尐↘猪︶ㄣ 提交于 2020-01-31 03:59:07

问题


I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder:

#include <windows.h>

#include <DemoPlugin.h>

/** A helper function to convert a char array into a
    LPBYTE array. */
LPBYTE message(const char* message, long* pLen)
{
  size_t length = strlen(message);
  LPBYTE mem = (LPBYTE) GlobalAlloc(GPTR, length + 1);
  for (unsigned int i = 0; i < length; i++)
  {
    mem[i] = message[i];
  }
  *pLen = length + 1;
  return mem;
}

long __stdcall Execute(char* pMethodName, char* pParams,
  char** ppBuffer, long* pBuffSize, long* pBuffType)
{
  *pBuffType = 1;

  if (strcmp(pMethodName, "") == 0)
  {
    *ppBuffer = (char*) message("Hello, World!",
  pBuffSize);
  }
  else if (strcmp(pMethodName, "Count") == 0)
  {
    char buffer[1024];
    int length = strlen(pParams);
    *ppBuffer = (char*) message(itoa(length, buffer, 10),
  pBuffSize);
  }
  else
  {
    *ppBuffer = (char*) message("Incorrect usage.",
  pBuffSize);
  }

  return 0;
}

Is is possible to make a plugin this way using Cython? Or even py2exe? The DLL just has to have an entry point, right?

Or should I just compile it natively and embed Python using elmer?


回答1:


I think the solution is to use both. Let me explain.

Cython makes it convenient to make a fast plugin using python but inconvenient (if at all possible) to make the right "kind" of DLL. You would probably have to use the standalone mode so that the necessary python runtime is included and then mess with the generated c code so an appropriate DLL gets compiled.

Conversely, elmer makes it convenient to make the DLL but runs "pure" python code which might not be fast enough. I assume speed is an issue because you are considering cython as opposed to simple embedding.

My suggestion is this: the pure python code that elmer executes should import a standard cython python extension and execute code from it. This way you don't have to hack anything ugly and you have the best of both worlds.


One more solution to consider is using shedskin, because that way you can get c++ code from your python code that is independent from the python runtime.



来源:https://stackoverflow.com/questions/4083150/using-cython-to-expose-functionality-to-another-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!