コールバック関数を必要とするCライブラリがあります。
void func( int *a, double *b, double *c, double *d )
a、b、cが入力され、「d」が出力されます。私のクラスは次のようになります。
class Test{
public:
Test()
{
a = 2;
ip = new int[128];
kd = new int[a];
c = new double[a];
dp = new double[26];
ja = NULL;
h = 1.0e-7;
hm = 1.0e-14;
ep = 1.0e-8;
tr = 1.0e-3;
for (int i = 0; i < 128; ++i)
ip[i] = 0;
b = 0.0;
t_e = 160.e0;
c[0] = 2.e0;
c[1] = 0.e0;
}
void my_func( int *a, double *b, double *c, double *d ) {
d[0] = some_value;
d[1] = some_other_value;
}
operator()()
{
auto member_func = std::bind( &Test::my_func, *this, _1, _2, _3, _4 );
external_function( ip, &a, &b, &t_e, c, &member_func, ja, &h, &hm, &ep, &tr, dp, kd, &ie );
}
private:
int *ip, *kd;
int a, ie;
double b, t_e;
double *c, *dp;
double h, hm, ep, tr;
void *ja;
};
正常にコンパイルされますが、実行すると「セグメンテーション違反(コアダンプ)」が発生します。なぜこれが起こるのか分かりません。
メンバー関数(my_func)を使用せずに、つまり、グローバルスコープで直接「func」を宣言、定義、および使用すると、正常に機能し、正しい結果が生成されます。
問題は、それぞれがクラスデータメンバーを変更して使用する必要があるため、Testクラスの複数のインスタンスを同時に並行して実行できないことです。残念ながら、「func」は引数を取りません。たとえば、(void * data)は、「テスト」へのキャストを許可します。
助けてもらえますか。どうもありがとう。
これは、単一のスレッドと複数のスレッドで機能します。
// C function
void func( int *a, double *b, double *c, double *d );
// Forward declaration of Test class
class Test;
// Thread local for thread safety
thread_local Test *p_global;
class Test{
public:
Test()
{
a = 2;
ip = new int[128];
kd = new int[a];
c = new double[a];
dp = new double[26];
ja = NULL;
h = 1.0e-7;
hm = 1.0e-14;
ep = 1.0e-8;
tr = 1.0e-3;
for (int i = 0; i < 128; ++i)
ip[i] = 0;
b = 0.0;
t_e = 160.e0;
c[0] = 2.e0;
c[1] = 0.e0;
}
void assign_this_pointer_to_global_and_dostuff()
{
p_global = this;
dostuff();
}
dostuff()
{
external_function( ip, &a, &b, &t_e, c, &func, ja, &h, &hm, &ep, &tr, dp, kd, &ie );
}
private:
int *ip, *kd;
int a, ie;
double b, t_e;
double *c, *dp;
double h, hm, ep, tr;
void *ja;
};
// C function
void func( int *a, double *b, double *c, double *d ) {
d[0] = some_value;
d[1] = some_other_value;
}
int main()
{
Test test;
std::thread t1( &Test::assign_this_pointer_to_global_and_dostuff, &test );
//Join the thread with the main thread
t1.join();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加