【发布时间】:2021-04-12 18:49:41
【问题描述】:
我的标题:
#define DLLExport __declspec (dllexport)
#define MAXCOLS 3
extern "C" {
typedef struct Matrix {
double** array; //contains all values
int rows;
int cols;
}Matrix;
DLLExport Matrix zeros(int num_rows, int num_cols);
DLLExport void print(Matrix mat);
DLLExport Matrix add(Matrix a, Matrix b);
DLLExport Matrix subtract(Matrix a, Matrix b);
DLLExport Matrix scalar_mult(Matrix a, double s);
DLLExport Matrix from_array(static int rows, static int cols, double a[][MAXCOLS]);
DLLExport Matrix slice_by_rows(Matrix y, int row_1, int row_2);
DLLExport Matrix vstack(Matrix a, Matrix b);
DLLExport Matrix transpose(Matrix a);
DLLExport Matrix diagonal(Matrix y);
DLLExport Matrix elem_mul(Matrix a, Matrix b);
DLLExport Matrix row_sum(Matrix y);
}
这是我的 CPP 文件(我省略了大部分功能):
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Header.h"
#define DLLExport __declspec (dllexport)
#define MAXCOLS 3
extern "C" {
DLLExport Matrix zeros(int num_rows, int num_cols) {
double** arr = (double**)calloc(num_rows, sizeof(double*));
for (int i = 0; i < num_rows; i++) {
arr[i] = (double*)calloc(num_cols, sizeof(double));
}
Matrix mat;
mat.array = arr;
mat.rows = num_rows;
mat.cols = num_cols;
return mat;
}
DLLExport void print(Matrix mat) {
for (int i = 0; i < mat.rows; i++) {
for (int j = 0; j < mat.cols; j++) {
printf("%f ", mat.array[i][j]);
}
printf("\n");
}
}
//...
}
这是我的 C# 文件中的内容:
//...
public unsafe struct Matrix
{
public double** array;
public int rows;
public int cols;
}
[DllImport("FastMatrix")]
public static extern unsafe Matrix zeros(int num_rows, int num_cols);
[DllImport("FastMatrix")]
public static extern void print(Matrix mat);
//...
我正在尝试在 Unity 中执行此操作,因此可能缺少一个设置。当我只有 .cpp 文件和一些基本函数(如添加两个整数、乘法等)时它可以工作,但是当我添加这些函数时它突然停止工作。
编辑:
看来我只需要重新启动 Unity。现在一切似乎都在工作,除了当我尝试在编辑器中点击“播放”时,Unity 完全崩溃了。我猜这是因为一些 C 指针在 C# 中没有正确播放。
【问题讨论】:
-
不用
__cdecl吗?另外:想知道为什么要在 C 中执行此操作,我认为如果您知道自己在做什么,它可以在 C# 中执行 -
C++ 函数是否使用修饰/损坏的名称导出?如果是,则必须在
DllImport.EntryPoint字段中指定修饰名称。此外,您的 C++ 函数可能使用__cdecl调用约定,但DllImport默认为__stdcall以与 Win32 API 兼容。请改用DllImport.CallingConvention属性指定Cdecl。 -
具体是哪些入口点或哪些点没有找到?发布错误消息。