[英]segmentation fault C and fortran
------ main.c--------- ------ main.c----------
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <string.h>
int main()
{
char* lib_name = "./a.out";
int array[5] = {1,2,3,4,5};
int size_a = sizeof(array)/sizeof(int);
void* handle = dlopen(lib_name, RTLD_NOW);
if (handle) {
printf("[%s] dlopen(\"%s\", RTLD_NOW): incarcare finalizata\n",
__FILE__, lib_name);
}
else {
printf("[%s] nu poate fi deschis: %s\n", __FILE__, dlerror());
exit(EXIT_FAILURE);
}
void (*subrutine_fortran)(int*, int*) = dlsym(handle, "putere");
if (subrutine_fortran) {
printf("[%s] dlsym(handle, \"_set_name\"): simbol gasit\n", __FILE__);
}
else {
printf("[%s] simbol negasit: %s\n", __FILE__, dlerror());
exit(EXIT_FAILURE);
}
subrutine_fortran(&array,&size_a);
//dlclose(handle);
for(int i=1;i<4;i++) {
array[i]=array[i]+1;
}
}
------ hello.f90 -------- ------ 你好.f90 --------
subroutine putere(a,h) bind(c)
use ISO_C_BINDING
implicit none
integer(c_int) :: h
integer(c_int), dimension(h) :: a
integer i
do concurrent (i=0:5)
a(i)=a(i)*10
end do
!write (*,*) a
end subroutine
When I do a loop through array elements:当我通过数组元素循环时:
for(int i=1;i<4;i++) {
array[i]=array[i]+1;
}
I get a segmentation fault.我得到一个分段错误。
It doesn't happen when I write:当我写时它不会发生:
array[3]=array[3]+1
Your C-code is this:你的 C 代码是这样的:
int array[5] = {1,2,3,4,5};
int size_a = sizeof(array)/sizeof(int);
subrutine_fortran(&array,&size_a);
and your Fortran code is this:你的 Fortran 代码是这样的:
subroutine putere(a,h) bind(c)
use ISO_C_BINDING
implicit none
integer(c_int) :: h
integer(c_int), dimension(h) :: a
integer i
do concurrent (i=0:5)
a(i)=a(i)*10
end do
!write (*,*) a
end subroutine
This is wrong a couple of ways - as Zack points out, Fortran arrays are 1-indexed (even when they come from somewhere else, like C).这是错误的几个方面 - 正如 Zack 指出的那样,Fortran arrays 是 1 索引的(即使它们来自其他地方,如 C)。 So this should start at 1. Also, if 0 was right, the size would be wrong.所以这应该从 1 开始。另外,如果 0 是正确的,那么大小就是错误的。 You want something like你想要类似的东西
do concurrent (i=1:h)
With that change, it works for me.有了这种变化,它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.