logo
down
shadow

Pass double pointer in a struct to CUDA


Pass double pointer in a struct to CUDA

By : Llewellyn
Date : November 25 2020, 07:22 PM
Hope that helps Questions like this get asked from time to time. If you search on the cuda tag, you'll find a variety of examples with answers. Here's one example.
In general, dynamically allocated data contained within structures or other objects requires special handling. This question/answer explains why and how to do it for the single pointer (*) case. Handling double pointers (**) is difficult enough that most people would recommend "flattening" the storage so that it can be handled by reference with a single pointer (*). If you really want to see how the double pointer (**) method works, review this question/answer. It's not trivial.
code :


Share : facebook icon twitter icon
CUDA: Is it OK to pass a pointer to struct to a device function?

CUDA: Is it OK to pass a pointer to struct to a device function?


By : xsba
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Inside of a kernel, is it OK to pass the address of a struct, which is declared inside the kernel, to a device function? The device function's argument is a pointer to a struct. , Yes, as the following program demonstrates:
code :
#include <stdio.h>

struct my_struct
{
  int x;
};

// foo receives its argument by pointer
__device__ void foo(my_struct *a)
{
  a->x = 13;
}

__global__ void kernel()
{
  my_struct a;
  a.x = 7;

  // expect 7 in the printed output
  printf("a.x before foo: %d\n", a.x);

  foo(&a);

  // expect 13 in the printed output
  printf("a.x after foo: %d\n", a.x);
}

int main()
{
  kernel<<<1,1>>>();
  cudaThreadSynchronize();
  return 0;
}
$ nvcc -arch=sm_20 test.cu -run
a.x before foo: 7
a.x after foo: 13
Passing an struct including a pointer to another struct, to kernel in CUDA

Passing an struct including a pointer to another struct, to kernel in CUDA


By : rlazom
Date : March 29 2020, 07:55 AM
To fix the issue you can do You're dereferencing a host pointer on the device. X is a valid device pointer.
But when you copied the X struct to the device, you copied x along with it, which contains a host pointer. When you dereference that pointer:
code :
collapsed x = X->x[0];
                 ^ this is dereferencing the x pointer
Improvements to dynamically allocate memory for a double pointer to struct inside a pointer to struct

Improvements to dynamically allocate memory for a double pointer to struct inside a pointer to struct


By : user3544410
Date : March 29 2020, 07:55 AM
this one helps. The problem is product is a pointer to a pointer, so if you intended to only an array of product under Inventory, you must use -> notation instead of . notation for price. (See example 1 below) If however, you intended to actually nest an array of struct Product under each pointer-to-Product you allocate (i.e. subproducts), see example 2:
Note: after each allocation, you must check the return from malloc to insure the allocation succeeded. (omitted in example 1 below for brevity, shown in full in example 2)
code :
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
} Product;

typedef struct {
    Product **product;
    int id;
} Inventory;

int main () {

    int i, j;
    int n1 = 2, n2 = 3;

    /* allocated / initiaize Inventory and Product */
    Inventory *inventory = malloc (n1 * sizeof *inventory);
    for (i = 0; i < n1; i++) 
    {
        inventory[i].id = i;
        inventory[i].product = malloc (n2 * sizeof *inventory[i].product);

        for (j = 0; j < n2; j++) 
        {
            inventory[i].product[j] = malloc (sizeof *inventory[i].product[j]);
            inventory[i].product[j]->price = (j + 1) * 2;
        }
    }

    /* print the inventory / procduct price */
    for (i = 0; i < n1; i++) 
    {
        printf ("\n product id : %d\n", inventory[i].id);
        for (j = 0; j < n2; j++) 
        {
            printf ("   price : %d\n", inventory[i].product[j]->price);
        }
    }

    /* free all memory */
    for (i = 0; i < n1; i++) 
    {
        for (j = 0; j < n2; j++) 
            free (inventory[i].product[j]);
        free (inventory[i].product);
    }
    free (inventory);

    return 0;
}
$ ./bin/allocate_ptr_in_struct

 product id : 0
   price : 2
   price : 4
   price : 6

 product id : 1
   price : 2
   price : 4
   price : 6
$ valgrind ./bin/allocate_ptr_in_struct
==10167== Memcheck, a memory error detector
==10167== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==10167== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==10167== Command: ./bin/allocate_ptr_in_struct
==10167==

 product id : 0
   price : 2
   price : 4
   price : 6

 product id : 1
   price : 2
   price : 4
   price : 6
==10167==
==10167== HEAP SUMMARY:
==10167==     in use at exit: 0 bytes in 0 blocks
==10167==   total heap usage: 9 allocs, 9 frees, 104 bytes allocated
==10167==
==10167== All heap blocks were freed -- no leaks are possible
==10167==
==10167== For counts of detected and suppressed errors, rerun with: -v
==10167== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
} Product;

typedef struct {
    Product **product;
    int id;
} Inventory;

int main () {

    int i, j, k;
    int n1 = 2, n2 = 3, n3 = 2;

    /* allocated / initiaize Inventory and Product */
    Inventory *inventory = malloc (n1 * sizeof *inventory);
    if (!inventory) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        exit (EXIT_FAILURE);
    }
    for (i = 0; i < n1; i++) 
    {
        inventory[i].id = i;
        if (!(inventory[i].product = malloc (n2 * sizeof *inventory[i].product))) {
            fprintf (stderr, "error: virtual memory exhausted.\n");
            exit (EXIT_FAILURE);
        }

        for (j = 0; j < n2; j++) 
        {
            if (!(inventory[i].product[j] = malloc (n3 * sizeof *inventory[i].product[j]))) {
                fprintf (stderr, "error: virtual memory exhausted.\n");
                exit (EXIT_FAILURE);
            }
            for (k = 0; k < n3; k++)
                inventory[i].product[j][k].price = (j + 1) * 2 * (k + 1);
        }
    }

    /* print the inventory / procduct price */
    for (i = 0; i < n1; i++) 
    {
        printf ("\n  Inventory id : %d\n", inventory[i].id);
        for (j = 0; j < n2; j++) 
        {
            printf ("\n    Product[%d]\n", j);
            for (k = 0; k < n3; k++)
                printf ("      subproduct[%d][%d] price : %d\n", 
                        j, k, inventory[i].product[j][k].price);
        }
    }

    /* free all memory */
    for (i = 0; i < n1; i++) 
    {
        for (j = 0; j < n2; j++) 
            free (inventory[i].product[j]);
        free (inventory[i].product);
    }
    free (inventory);

    return 0;
}
$ ./bin/allocate_ptr_in_struct

  Inventory id : 0

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12

  Inventory id : 1

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12
$ valgrind ./bin/allocate_ptr_in_struct
==23024== Memcheck, a memory error detector
==23024== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==23024== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==23024== Command: ./bin/allocate_ptr_in_struct
==23024==

  Inventory id : 0

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12

  Inventory id : 1

    Product[0]
      subproduct[0][0] price : 2
      subproduct[0][1] price : 4

    Product[1]
      subproduct[1][0] price : 4
      subproduct[1][1] price : 8

    Product[2]
      subproduct[2][0] price : 6
      subproduct[2][1] price : 12
==23024==
==23024== HEAP SUMMARY:
==23024==     in use at exit: 0 bytes in 0 blocks
==23024==   total heap usage: 9 allocs, 9 frees, 128 bytes allocated
==23024==
==23024== All heap blocks were freed -- no leaks are possible
==23024==
==23024== For counts of detected and suppressed errors, rerun with: -v
==23024== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
How to pass/access a double pointer to/from a struct?

How to pass/access a double pointer to/from a struct?


By : william
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Firstly, in direct answer to your question, if you define a matrix in that way and want to store its pointer in a struct, you can do it via a direct assignent. Carrying on from your example, you could make the doublePointer member of a struct AMessage point to the memory you've allocated at c simply via something like this:
code :
struct AMessage am;
am.doublePtr = c;
double matrix[ROW][COL];
struct AMessage
{
     char MessageId;
     double matrix[ROW][COL];
};
double *c = malloc(ROW * COL * sizeof(*c));
double a = c[ROW * j + i];
double a = d[j][i];
double (*d)[ROW];
struct AMessage 
{
     char MessageId;
     double (*matrix)[ROW];
}
struct AMessage am;
am.matrix = malloc(ROW * COL * sizeof(*am.matrix));
am.matrix[j][i] = 42; // Assigns 42 to row j, column i 
Cast C struct double pointer to a Swift struct unsafe pointer

Cast C struct double pointer to a Swift struct unsafe pointer


By : Praveen M
Date : March 29 2020, 07:55 AM
it fixes the issue Let's think about that in terms of what's happening in C. When I do a cast of pointers in C, the data that represents the pointer type will now be treated as a pointer of a different type. The value of the pointer doesn't change, just how you treat it.
Swift doesn't like to do this kind of thing and doesn't encourage you to do it because while cheap, it's a fundamentally unsafe thing to do and can lead to corrupting data, jumping into space, bus errors, etc.
code :
let a:UnsafeMutablePointer<SomeType> = fetchASomeTypePointer()
let b = unsafeBitCast(a, to: UnsafeMutablePointer<SomeOtherType>.self)
Related Posts Related Posts :
  • What could be causing my WhatsApp Stickers Pack not to work?
  • How Can I Reorder/Sort The Collections List in Directus?
  • Is this language generic/mighty enough to be used for a generic game AI?
  • graphite, use regular expressions to select the target, or an alternative
  • subtract functions with type real in ml
  • how to filter '(' in navision 2013
  • sending sms from a mobile browser
  • NuGet behind firewall
  • Gstreamer hangs while generating timelapse from JPEGs on Raspberry pi
  • How to retrieve total view count of large number of pages combined from the GA API
  • Websites rich with exercices or explanation for SML?
  • Is there a TempData equivalent in ServiceStack?
  • scipy-0.12.0 failing to install on mountain lion using python setup.py install
  • Looking for simplest option to render Razor cshtml pages in a console application without any web server
  • Evaluating variables at a specific time in Modelica
  • When I run the Application, only "web" engine is running in GlassFish. "webservices" is not started
  • How To Set MIME Type Of Google Drive File
  • Remove Missing Values in Weka
  • Reloading a UICollectionView using reloadData method returns immediately before reloading data
  • carrot2 - can I cluster documents from a folder?
  • StreamSocket has no Close Implementation in C#
  • Rails, Foundation 4, Respond.js not working properly in IE8
  • How can i create imagesurface from cairo xlib's Graphics Context using cairo and x11 Api's?
  • CKEditor "overflow: scroll" on parent causes toolbar to freeze at initial position
  • Differences between components and controls in ENYO
  • Photoshop making isometric?
  • Does Intel IPP 8.0 support in-place operations?
  • What is Object dictionary in CANOpen?
  • Example of orbBasic Indexed User Variables
  • convert to ABSOLUTE in logback
  • How to conditionally download file using p:fileDownload
  • Error on pod install
  • Set HTTP GET Parameters in Finagle
  • different attack that uses sql injection
  • How can I change my xampp username not as 'root'
  • AMQP Content header payload structure
  • Apache POI formula evaluation not working for Excel IF
  • How can I trace RESTEasy's dispatch?
  • Map Freezes on iOS 7 with Google Maps SDK 1.4
  • Comparing lists, is the subset list within the first list
  • Non-ascii character highlight in Sublime Text 2
  • Installing Magit in Aquamacs
  • Receiving error - System.Net.Mail.SmtpException: 4.3.2 try again later
  • Coreaudio render callback in monotouch
  • The command 'yarn --v' also initiates 'yarn install' and installs packages automatically. Why is this happening?
  • save multiple matches in a list (grep or awk)
  • Can a number register be used in a groff request?
  • Mapping FAQ with RASA for large dataset (2000+)
  • Fragment not receiving LiveData updates after remove + add
  • FitText.js makes text bigger rather than smaller
  • ARM - Implementing stack with load/store multiple register values
  • How to check if a ChromeCast Session is already in progress
  • ngForm inside a Carousel Slide in UI Bootstrap not working
  • Clearing attributes in Tritium
  • "vagrant up" failing: Vagrant VM failed to remain in the running state
  • ftsearch returning empty docs
  • What are the advantages of setting "hive.exec.parallel" to false in Hive ?
  • Creating a root certificate in FiddlerCore
  • How to access app.config in a blueprint?
  • DB2 RECORDSET table name converted to uppercase
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org