Issues and best practices when using Pico SDK/API (shared libraries/dll's)

Post general discussions on using our drivers to write your own software here
Post Reply
AndrewA
PICO STAFF
PICO STAFF
Posts: 401
Joined: Tue Oct 21, 2014 3:07 pm

Issues and best practices when using Pico SDK/API (shared libraries/dll's)

Post by AndrewA »

Invalid data, inconsonant results and crashes/exceptions can be caused by a number issues in your code.
Please check this list of best practices it may fix your issue when using the API/SDK.

1) Pass Unmanaged memory to data Buffers.
The API functions use unmanaged memory to write data into, passing managed memory (which is garbage collected) will give inconsonant results.

C#
In in our C# examples we create a pinned arrays and pass these to psXXXXSetDataBuffer(s) functions.
Our pinned array function is here-
https://github.com/picotech/picosdk-c-s ... edArray.cs
This uses the GCHandle.Alloc method-
https://learn.microsoft.com/en-us/dotne ... ew=net-8.0

LabVIEW
In the shared LabIVEW sub repository we have created high and low level functions to use unmanaged memory with the API.
https://github.com/picotech/picosdk-ni-labview-shared
These use the underlying DSNewPtr, MoveBlock and DSDisposePtr, LabVIEW functions.
We are in the process of updating all our LabVIEW examples to use these functions.

2) Check all API functions are declared correctly with the correct data types.
See Data types by Programming language-
topic14387.html
Refer to the C header files in the SDK installation directory.

C# uses DllImport for this.
https://learn.microsoft.com/en-us/dotne ... ew=net-8.0

3) Check all PICO_STATUS codes returned from the API function.
Refer to the PicoStatus.h C header file in the SDK installation directory.
Note some of our older API's do not return the PICO_STATUS enum values.
So you need to check each of those functions individually and handle any error values returned. (Refer to the units programmers guide)

4) Threading
Our drivers are thread safe.
In GUI applications you could be calling API functions in more than one thread.
But if you call an API function before another is finished the function will return PICO_STATUS code-

Code: Select all

// A driver function has already been called and not yet finished.
// Only one call to the driver can be made at any one time.
#define PICO_DRIVER_FUNCTION                        0x00000043UL
But its best practice to lock the API functions to one thread-

C#
Use a single object for example-

Code: Select all

private readonly object DriverLock = new object();
Example calling an API function-

Code: Select all

      lock (DriverLock)
      {
        return SafeNativeMethods.ChangePowerSource(DirectHandle, powerState);
      }
See-
https://learn.microsoft.com/en-us/dotne ... -practices
Regards Andrew
Technical Specialist

Post Reply